1

首先,我创建了一个 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 的外键之外,其余的外键都很好。谁能告诉我问题出在哪里?非常感谢!!

4

1 回答 1

1
FOREIGN KEY(SectionNo) REFERENCES CourseSections(SectionNo)

应该可以工作,但其他外键不会,因为它们实际上没有索引;它们是综合指数的较低部分。复合索引仅按照创建方式的顺序用于列。您需要在 CourseSections.Year 和 CourseSections.Semester 上创建唯一索引,或者更有可能创建一个像这样的单个复合外键:

FOREIGN KEY(SectionNo, Year, Semester) REFERENCES CourseSections(SectionNo, Year, Semester)
于 2012-11-13T21:10:27.647 回答