无法添加外键为主键的外键约束

时间:2014-12-03 04:21:02

标签: mysql sql database foreign-keys

我正在接受

Error Code: 1215. Cannot add foreign key constraint 0.172 sec

我不知道自己做错了什么。我确保外键是主键。 我的sql:

CREATE TABLE Student (
StudentID INT(6) NOT NULL,
StudName VARCHAR(15) NOT NULL,
StudEmail VARCHAR(15) NOT NULL,
StudeHomeNum INT(10) NOT NULL,
StudCellPhoneNum INT(10) NOT NULL,
CourseCode INT(6) NOT NULL,
ProgramCode INT(6) NOT NULL,
PRIMARY KEY (StudentID),
FOREIGN KEY (CourseCode)
    REFERENCES Course (CourseCode)
);

CREATE TABLE Course (
CourseCode INT(6) PRIMARY KEY NOT NULL,
CourseName VARCHAR(15) NOT NULL,
Prequisites VARCHAR(15) NOT NULL
);

1 个答案:

答案 0 :(得分:0)

由于CourseCode表中的Student代码列引用了Course表,因此您必须先创建Course表。更改您的SQL代码如下

CREATE TABLE Course (
CourseCode INT(6) PRIMARY KEY NOT NULL,
CourseName VARCHAR(15) NOT NULL,
Prequisites VARCHAR(15) NOT NULL
);

CREATE TABLE Student (
StudentID INT(6) NOT NULL,
StudName VARCHAR(15) NOT NULL,
StudEmail VARCHAR(15) NOT NULL,
StudeHomeNum INT(10) NOT NULL,
StudCellPhoneNum INT(10) NOT NULL,
CourseCode INT(6) NOT NULL,
ProgramCode INT(6) NOT NULL,
PRIMARY KEY (StudentID),
FOREIGN KEY (CourseCode)
    REFERENCES Course (CourseCode)
);