简体   繁体   English

SQL错误-引用的表中没有主键或候选键

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

Firstly I created a CourseSections table like below: 首先,我创建了一个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)
);

Then I created another table that has foreign keys referencing to table CourseSections keys: 然后,我创建了另一个表,该表具有引用表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)  

); );

Then I'm getting an error message saying 然后我收到一条错误消息说

    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'.

The rest foreign keys are all fine except the ones referencing to the table CourseSections. 除了那些引用表CourseSections的外键,其余的外键都可以。 Can anyone tell me where the problem is? 谁能告诉我问题出在哪里? Very much appreciated!! 非常感谢!!

FOREIGN KEY(SectionNo) REFERENCES CourseSections(SectionNo)

should work, but the other foreign keys will not since they don't really have an index; 应该起作用,但是其他外键实际上没有索引,因此不会起作用; they are lower parts of a composite index. 它们是综合索引的下部。 A composite index is used for columns only in order of how it was created. 复合索引仅按创建索引的顺序用于列。 You would either needs to make unique indexes on CourseSections.Year and CourseSections.Semester, or, more likely, create a single composite foreign key like this: 您可能需要在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