MySQL中的外键:错误1005 [英] Foreign Key in MySQL : ERROR 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)
我搜索了一下,发现
我觉得我错过了一些相当基本的东西,但我看不出来。任何建议吗? 您应该在被引用的表 I'm a bit confused about adding foreign keys in MySQL What I'm trying to do is reference the Students primary key with: However, what I get is 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: 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
这篇关于MySQL中的外键:错误1005的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
|学生| 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)
);
CREATE TABLE Enrolled(sid CHAR(20), cid CHAR(20), grade CHAR(2), PRIMARY KEY (sid, cid), FOREIGN KEY (sid) REFERENCES Students);
ERROR 1005 (HY000): Can't create table 'test_db.Enrolled' (errno: 150)
| 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 |
REFERENCES Students(sid)
. So you have to change your code to below solutionCREATE TABLE Enrolled
(
sid CHAR(20),
cid CHAR(20),
grade CHAR(2),
PRIMARY KEY (sid, cid),
FOREIGN KEY (sid) REFERENCES Students(sid)
);