首先,我创建了一个如下所示的CourseSections表:
Create Table CourseSections(
CourseNo Integer NOT NULL CHECK(CourseNo BETWEEN 100 AND 999),
SectionNo Integer NOT NULL,
InstructorNo Integer NOT NULL,
Year Integer NOT NULL,
Semester Integer NOT NULL,
FOREIGN KEY(CourseNo) REFERENCES Courses(CourseNo),
PRIMARY KEY(SectionNo, Year, Semester)
);
然后我创建了另一个具有引用表CourseSections键的外键的表:
Create Table Enrollments(
CourseNo Integer NOT NULL CHECK(CourseNo BETWEEN 100 AND 999),
Semester Integer NOT NULL,
Year Integer NOT NULL,
SectionNo Integer NOT NULL,
FOREIGN KEY(CourseNo) REFERENCES Courses(CourseNo),
FOREIGN KEY(Year) REFERENCES CourseSections(Year),
FOREIGN KEY(Semester) REFERENCES CourseSections(Semester),
FOREIGN KEY(SectionNo) REFERENCES CourseSections(SectionNo)
);
然后我收到一条错误消息
There are no primary or candidate keys in the referenced table 'CourseSections'
that match the referencing column list in the foreign key
FK__Enrollment__Year__3890146B'.
其他外键都很好,除了引用表CourseSections的外键。谁能告诉我问题出在哪里?非常感谢!!
答案 0 :(得分:1)
FOREIGN KEY(SectionNo) REFERENCES CourseSections(SectionNo)
应该可行,但其他外键不会,因为他们没有真正的索引;它们是综合指数的较低部分。复合索引仅按列的创建顺序用于列。您可能需要在CourseSections.Year和CourseSections.Semester上创建唯一索引,或者更有可能创建一个这样的复合外键:
FOREIGN KEY(SectionNo, Year, Semester) REFERENCES CourseSections(SectionNo, Year, Semester)