MySQL错误1005 - 外键无法正常工作

时间:2017-10-10 11:22:21

标签: mysql foreign-keys mysql-error-1005

我收到错误代码1005,这意味着我的外键存在问题?任何人都可以向我解释这个!

CREATE SCHEMA test;
Use test;

CREATE TABLE student
(
stud_id INT(7) NOT NULL , 
stud_name VARCHAR(30) NOT NULL , 
PRIMARY KEY (stud_id)
);
CREATE TABLE subject
(
subj_code VARCHAR(7) NOT NULL ,   
PRIMARY KEY (subj_code)
);
CREATE TABLE grade
(
stud_id INT(7) NOT NULL , 
subj_code VARCHAR(7) NOT NULL , 
semester INT(1) NOT NULL , 
year YEAR(4) NOT NULL , 
grade VARCHAR(4) NOT NULL , 
PRIMARY KEY (stud_id, subj_code, semester, year) ,
FOREIGN KEY (stud_id) REFERENCES student(student_id)
);
CREATE TABLE subj_enrolment
(
stud_id INT(7) NOT NULL , 
subj_code VARCHAR(7) NOT NULL , 
semester INT(1) NOT NULL , 
year YEAR(4) NOT NULL , 
comment VARCHAR(300) , 
PRIMARY KEY (stud_id, subj_code, semester, year) ,
FOREIGN KEY (stud_id) REFERENCES student(student_id) ,
FOREIGN KEY (subj_code) REFERENCES subject(subject_code)
);

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

您使用错误的列名称引用student_id不是student表中的列名,它必须是stud_id。 subject_code也是如此。我已经纠正了它们并发布在下面。

CREATE SCHEMA test;
Use test;

CREATE TABLE student
(
 stud_id INT(7) NOT NULL , 
 stud_name VARCHAR(30) NOT NULL , 
 PRIMARY KEY (stud_id)
);
CREATE TABLE subject
(
 subj_code VARCHAR(7) NOT NULL ,   
 PRIMARY KEY (subj_code)
);
CREATE TABLE grade
(
 stud_id INT(7) NOT NULL , 
 subj_code VARCHAR(7) NOT NULL , 
 semester INT(1) NOT NULL , 
 year YEAR(4) NOT NULL , 
 grade VARCHAR(4) NOT NULL , 
 PRIMARY KEY (stud_id, subj_code, semester, year) ,
 FOREIGN KEY (stud_id) REFERENCES student(stud_id )
);
CREATE TABLE subj_enrolment
(
 stud_id INT(7) NOT NULL , 
 subj_code VARCHAR(7) NOT NULL , 
 semester INT(1) NOT NULL , 
 year YEAR(4) NOT NULL , 
 comment VARCHAR(300) , 
 PRIMARY KEY (stud_id, subj_code, semester, year) ,
 FOREIGN KEY (stud_id) REFERENCES student(student_id) ,
 FOREIGN KEY (subj_code) REFERENCES subject(subj_code )
);