我按照上述顺序创建了以下表格。但是当我创建enrolls
表时出现错误。
我知道它与外键约束有关。但我觉得我做得对。我不知道我做错了什么:
create table Course (
CourseNo integer(10),
CourseName varchar(50),
Department varchar(20),
primary key (CourseNo)) Engine = InnoDB;
create table Section (
CourseNo integer(10),
SectionNo integer(10),
Instructor varchar(50),
primary key (CourseNo, SectionNo),
foreign key (CourseNo) references Course(CourseNo)) Engine = InnoDB;
create table Student (
SSN varchar(9),
FirstName char(50),
LastName char(50),
Street char(50),
City char(50),
State char(50),
Zip char(5),
primary key (SSN)) Engine = InnoDB;
create table Enrolls (
SSN varchar(9),
SectionNo integer(10),
CourseNo integer(10),
foreign key (SectionNo) references Section(SectionNo),
foreign key (CourseNo) references Section(CourseNo),
foreign key (SSN) references Student(SSN),
primary key (SSN, SectionNo, CourseNo)) Engine = InnoDB;
答案 0 :(得分:1)
不,你在定义外键时做错了。以下是精确的
foreign key (SectionNo) references Section(SectionNo)
foreign key (CourseNo) references Section(CourseNo),
在Section
表格中,您有两列定义为主键primary key (CourseNo, SectionNo)
。因此,在你的FK中,你必须用两个字段/列来引用它们,如
foreign key (CourseNo, SectionNo) references Section(CourseNo, SectionNo)
哪一项意味着,您的最后一张桌子必须以这种方式创建:
create table Enrolls (
SSN varchar(9),
SectionNo integer(10),
CourseNo integer(10),
primary key (SSN, SectionNo, CourseNo),
foreign key (CourseNo, SectionNo) references Section(CourseNo, SectionNo)
) Engine = InnoDB;
在此处查看演示小提琴http://sqlfiddle.com/#!2/741b2