簡體   English   中英

SQL錯誤-引用的表中沒有主鍵或候選鍵

[英]SQL error - There are no primary or candidate keys in the referenced table

首先,我創建了一個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的外鍵,其余的外鍵都可以。 誰能告訴我問題出在哪里? 非常感謝!!

FOREIGN KEY(SectionNo) REFERENCES CourseSections(SectionNo)

應該起作用,但是其他外鍵實際上沒有索引,因此不會起作用; 它們是綜合索引的下部。 復合索引僅按創建索引的順序用於列。 您可能需要在CourseSections.Year和CourseSections.Semester上創建唯一索引,或者更有可能創建一個復合外鍵,如下所示:

FOREIGN KEY(SectionNo, Year, Semester) REFERENCES CourseSections(SectionNo, Year, Semester)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM