当我尝试为表声明多个外键时,我不断收到错误“#1215 - 无法添加外键约束”。我知道可以在表中声明多个外键,所以我不确定为什么我收到错误。我很确定我的错误与引用多值主键有关,但我不确定如何修复它。非常感谢所有帮助,并提前感谢您!
编辑:前4个表正常工作。最后4个是我遇到麻烦的。
以下是我的表格:
CREATE TABLE Course (
CourseNo INT NOT NULL,
CourseName VARCHAR(40) NOT NULL,
Department VARCHAR(40) NOT NULL,
PRIMARY KEY(CourseNo)
);
CREATE TABLE Student (
SSN INT NOT NULL,
FirstName VARCHAR(15) NOT NULL,
LastName VARCHAR(30) NOT NULL,
Street VARCHAR(40) NOT NULL,
City VARCHAR(40) NOT NULL,
State VARCHAR(30) NOT NULL,
Zip MEDIUMINT NOT NULL,
PRIMARY KEY(SSN)
);
CREATE TABLE ClassRoom (
RoomNo INT NOT NULL,
Building VARCHAR(25) NOT NULL,
Capacity INT NOT NULL,
/* CONSTRAINT pk_ClassID */ PRIMARY KEY(RoomNo, Building)
);
CREATE TABLE Section (
CourseNumber INT NOT NULL,
SectionNo INT NOT NULL,
Instructor VARCHAR(40) NOT NULL,
/*CONSTRAINT pk_SectionID*/ PRIMARY KEY(CourseNumber, SectionNo),
FOREIGN KEY (CourseNumber) REFERENCES Course(CourseNo)
);
CREATE TABLE Enrolls (
StuSSN INT NOT NULL,
SecNo INT NOT NULL,
CNo INT NOT NULL,
/* CONSTRAINT pk_EnrollID */ PRIMARY KEY(StuSSN, SecNo, CNo),
FOREIGN KEY (StuSSN) REFERENCES Student(SSN),
FOREIGN KEY (SecNo) REFERENCES Section(SectionNo),
FOREIGN KEY (CNo) REFERENCES Course(CourseNo)
);
CREATE TABLE Exam (
CNum INT NOT NULL,
SectionNum INT NOT NULL,
ExamNo INT NOT NULL,
E_Date DATE NOT NULL,
E_Time TIME NOT NULL,
/* CONSTRAINT pk_ExamID */ PRIMARY KEY(CNum, SectionNum, ExamNo),
FOREIGN KEY (CNum) REFERENCES Course(CourseNo),
FOREIGN KEY (SectionNum) REFERENCES Section(SectionNo)
);
CREATE TABLE Takes (
StudentSSN INT NOT NULL,
CourseNum INT NOT NULL,
SecNum INT NOT NULL,
ExamNum INT NOT NULL,
Result TINYINT NOT NULL,
/* CONSTRAINT pk_TakesID */ PRIMARY KEY(StudentSSN, CourseNum, SecNum, ExamNum),
FOREIGN KEY (StudentSSN) REFERENCES Student(SSN),
FOREIGN KEY (CourseNum) REFERENCES Course(CourseNo),
FOREIGN KEY (SecNum) REFERENCES Section(SectionNo),
FOREGIN KEY (ExamNum) REFERENCES Exam(ExamNo)
);
CREATE TABLE ConductedIn (
RoomNum INT NOT NULL,
Build VARCHAR(25) NOT NULL,
CNumber INT NOT NULL,
SectionNumber INT NOT NULL,
ExamNumber INT NOT NULL,
/* CONSTRAINT pk_ConductedID */ PRIMARY KEY(RoomNum, Build, CNumber, SectionNumber, ExamNumber),
FOREIGN KEY (RoomNum) REFERENCES ClassRoom(RoomNo),
FOREIGN KEY (Build) REFERENCES ClassRoom(Building),
FOREIGN KEY (CNumber) REFERENCES Course(CourseNo),
FOREIGN KEY (SectionNumber) REFERENCES Section(SectionNo),
FOREIGN KEY(ExamNumber) REFERENCES Exam(ExamNo)
);
答案 0 :(得分:1)
我会在这里向您推荐更多详情:MySQL Foreign Key Error 1005 errno 150
基本上您的问题是,在Section
表中,您有一个复合主键PRIMARY KEY(CourseNumber, SectionNo)
,在Enrolls
表格中,您尝试引用字段SectionNo
表Section
,但该字段没有索引。任何引用的字段都必须有索引。
因此,请确保您作为外键引用的任何字段都有自己的索引(例如PRIMARY(fieldname)
UNIQUE(fieldname)
INDEX(fieldname)
)