MySQL中的外键:错误1005 [英] Foreign Key in MySQL : ERROR 1005

查看:198
本文介绍了MySQL中的外键:错误1005的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图做的是引用学生主键:

  CREATE TABLE已注册(sid CHAR(20),cid CHAR(20),grade CHAR(2),PRIMARY KEY(sid,cid),FOREIGN KEY(sid)参考学生); 

然而,我得到的是

错误1005(HY000):无法创建表'test_db.Enrolled'(errno:150)

我搜索了一下,发现

  |学生| CREATE TABLE学生(
sid char(20)NOT NULL DEFAULT'',
name char(20)DEFAULT NULL,
登录字符(10)DEFAULT NULL,
年龄int 11)DEFAULT NULL,
gpa float DEFAULT NULL,
PRIMARY KEY(sid)
)ENGINE = InnoDB DEFAULT CHARSET = latin1 |

我觉得我错过了一些相当基本的东西,但我看不出来。任何建议吗?

您应该在被引用的表
之后添加被引用的列名。REFERENCES Students SID)。所以你必须改变你的代码到下面的解决方案

$ p $ CREATE TABLE登记

sid CHAR(20 ),
cid CHAR(20),
等级CHAR(2),
PRIMARY KEY(sid,cid),
FOREIGN KEY(sid)REFERENCES学生(sid)
);


I'm a bit confused about adding foreign keys in MySQL

What I'm trying to do is reference the Students primary key with:

CREATE TABLE Enrolled(sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid, cid), FOREIGN KEY (sid) REFERENCES Students);

However, what I get is

ERROR 1005 (HY000): Can't create table 'test_db.Enrolled' (errno: 150)

I searched around and found

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

However, my Students table already has a primary key so this should not be an issue:

| Students | CREATE TABLE Students (
  sid char(20) NOT NULL DEFAULT '',
  name char(20) DEFAULT NULL,
  login char(10) DEFAULT NULL,
  age int(11) DEFAULT NULL,
  gpa float DEFAULT NULL,
  PRIMARY KEY (sid)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |

I feel like I'm missing something fairly basic but I can't appear to spot it. Any advice?

解决方案

You should add referenced column name after referenced table REFERENCES Students(sid). So you have to change your code to below solution

CREATE TABLE Enrolled
(
  sid CHAR(20), 
  cid CHAR(20), 
  grade CHAR(2), 
  PRIMARY KEY (sid, cid), 
  FOREIGN KEY (sid) REFERENCES Students(sid)
);

这篇关于MySQL中的外键:错误1005的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆