Reputation: 6835
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?
Upvotes: 3
Views: 290
Reputation: 3391
What about making the referenced column explicit? Something like:
CREATE TABLE Enrolled(
sid CHAR(20),
cid CHAR(20),
grade CHAR(2),
PRIMARY KEY (sid, cid),
FOREIGN KEY (sid) REFERENCES Students (sid)
);
Look at FOREIGN KEY (sid) REFERENCES Students (sid)
, last line. Also note that if the foreign key is a single column you can specify it just after the column type:
CREATE TABLE Enrolled(
sid CHAR(20) REFERENCES Students (sid),
...
Upvotes: 1
Reputation: 25753
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)
);
Upvotes: 3