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
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)
);