[英]Foreign Key SQL: How can I reference two attributes in one table to a composite primary key that contains 3 columns in the other table?
CREATE TABLE SECTION,`
SectionNo int,
Semester CHAR(7),
CourseID CHAR(8),
PRIMARY KEY (SectionNo, Semester, CourseID),
FOREIGN KEY (CourseID) REFERENCES COURSE (CourseID),
);
CREATE TABLE REGISTRATION(
StudentID int,
SectionNo int,
Semester char(7),
PRIMARY KEY (StudentID, SectionNo, Semester),
FOREIGN KEY (SectionNo, Semester) REFERENCES Section (SectionNo, Semester),
Underline is coming up under "Section". 下划线显示在“部分”下。 The error says, "There are no primary or candidate keys in the referenced table 'Section' that match the referencing column list in the foreign key." 该错误显示:“在引用表'Section'中没有与外键中的引用列列表匹配的主键或候选键。” How do I fix this?! 我该如何解决?!
FOREIGN KEY (StudentID) REFERENCES Student (StudentID),
);
Probably 大概
Judging (uh... guessing) from your chosen names, a student ought to register in a certain semester in a certain section of a certain course . 从您选择的名字来判断(嗯...猜),学生应该在某个课程的某个部分的某个学期中进行注册。 So your registration table is probably missing a course column. 因此,您的注册表可能缺少课程列。
There would be a 3-column FK to the 3-column PK. 3列PK会有3列FK。 Also the registration PK would be all 4 columns. 同样,注册PK将全部为4列。
But if 但是如果
If you were recording just a semester and course, that would be an inclusion dependency (IND) from REGISTRATION to COURSE. 如果您仅记录一个学期和一个课程,那将是从REGISTRATION到COURSE的包含依赖关系(IND)。 A foreign key (FK) is an IND to a key. 外键(FK)是键的IND。 (Well, in SQL it's an IND to a superkey, SQL KEY/UNIQUE.) An IND from columns to others means every source subrow value ahs to appear as a target subrow value. (好吧,在SQL中,它是超键SQL KEY / UNIQUE的IND。)从列到其他的IND意味着每个源子行值ahs都将作为目标子行值出现。 Ie the projection of the source on its IND columns MINUS the projection of the target on its IND columns has to be empty. 即,源在其IND列上的投影减去目标在其IND列上的投影必须为空。
That IND means every REGISTRATION semester-course subrow value has to appear as a COURSE subrow value. IND表示每个REGISTRATION学期课程的子行值都必须显示为COURSE子行值。 Which means 意思是
NOT EXISTS (
SELECT Semester,Course FROM REGISTRATION
EXCEPT SELECT Semester,Course FROM COURSE
)
If you have no EXCEPT/MINUS then there's an idiom with LEFT JOIN. 如果您没有EXCEPT / MINUS,那么LEFT JOIN就是一个成语。
You wish 你希望
You can't easily express this constraint in most SQL DBMSs. 您很难在大多数SQL DBMS中表达此约束。 (Although the standard describes the functionality.) You usually have to use triggers on updates to check all but a small number of non-trivial constraints in SQL. (尽管标准描述了功能。)通常,您必须在更新时使用触发器来检查SQL中除少数非平凡约束以外的所有约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.