简体   繁体   English

复合主键的外键

[英]Foreign Key to Composite Primary Key

I have a problem with foreign keys. 我的外键有问题。

The master table is: 主表是:

Course (courseName, courseId) 

and PK is courseId 而PK则是courseId

The second table is: 第二个表是:

Section (sectionId, courseId) 

and PK is (sectionId, courseID) , FK is courseID reference Course(courseId) 和PK是(sectionId, courseID) ,FK是courseID reference Course(courseId)

And the problem table is: 问题表是:

GradeReport (studentId, sectionId, courseId, grade) 

and PK is (studentID, sectionID, courseID) 和PK是(studentID, sectionID, courseID)

The FK's are FK是

  • courseId reference Course(courseID)
  • sectionId reference Section(sectionID)

( no permisson for (courseId, sectionId) reference Section(courseId, sectionID)) 没有 (courseId,sectionId)参考部分(courseId,sectionID))

The first FK is OK! 第一个FK没关系! But the second one gives me an error: 但第二个给了我一个错误:

ORA-02270: no matching unique or primary key for this column-list ORA-02270:此列列表没有匹配的唯一键或主键

How can I solve this problem? 我怎么解决这个问题?

Since the primary key of Section is (sectionId, courseID), the foreign key constraint of GradeReport must be (sectionID, courseID). 由于Section的主键是(sectionId,courseID),GradeReport的外键约束必须是(sectionID,courseID)。

In fact you will not need a foreign key constraint on GradeReport referencing Course, since the courseID will be in this foreign key constraint. 事实上,您不需要在GradeReport引用课程上使用外键约束,因为courseID将在此外键约束中。

I don't understand the question fully, but if I had these tables my foreign keys would be: 我不完全理解这个问题,但如果我有这些表,我的外键将是:

  • Section (which I think is OK for you already) 部分(我觉得你已经可以了)

     FOREIGN KEY ..name.. REFERENCES Course(CourseID) 
  • GradeReport (which is where I think you have the problem) GradeReport(这是我觉得你有问题的地方)

     FOREIGN KEY ..name.. REFERENCES Section(SectionID, CourseID) 

You don't need a separate Foreign Key for GradeReport.CourseID because it's already part of the SectionID, CourseID foreign key to Section , and Section.CourseID can be trusted because of the Section table's foreign key with Course . 对于GradeReport.CourseID您不需要单独的外键,因为它已经是SectionSectionID, CourseID外键的一部分,而Section.CourseID可以被信任,因为Section表的外键带有Course

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM