duanlou2917 2014-03-31 11:40
浏览 181
已采纳

在我的情况下如何在mysql中定义FOREIGN KEY约束不起作用

I need to know about how to declare foreign key in mysql and how it works. Here's one sample first table contains name, age the second table refer the first tables name. While I run this, I receive error only.

<?php
$conn=new mysqli("localhost","root","12345");
$sql="USE new";
$conn->query($sql);
$sql="CREATE TABLE test(name varchar(20),age integer)";
$conn->query($sql);
$sql="CREATE TABLE test2(name varchar(10),FOREIGN KEY (name) REFERENCES test     (name)";
if($conn->query($sql)==true)
{
    header('Locaton:test3.html');
}
else
{
    echo "error";
}
?> 

Can anyone help me?

  • 写回答

4条回答 默认 最新

  • douchen4547 2014-03-31 11:45
    关注

    foreign key must refrence from a Primary key then use a primary key on name,

    $sql="CREATE TABLE test(name varchar(20) PRIMARY KEY,age integer)";
    

    and also change on

    $sql="CREATE TABLE test2(name varchar(10),FOREIGN KEY (name) REFERENCES test(name))";
    

    if your name field have chance to duplicate then take one another field id and use it to reference.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)