您的关系是一对多的,即 1 个主题可以有许多先决条件,因此您应该使用另一个表。例如
CREATE TABLE SubjectPrerequisite
( Primary_Subject_Code VARCHAR(7) NOT NULL,
Prerequisite_Subject_Code VARCHAR(7) NOT NULL,
CONSTRAINT PK_SubjectPrerequisite PRIMARY KEY (Primary_Subject_Code, Prerequisite_Subject_Code),
CONSTRAINT FK_SubjectPrerequisite_Primary_Subject_Code FOREIGN KEY (Primary_Subject_Code) REFERENCES Subject (Subject_Code),
CONSTRAINT FK_SubjectPrerequisite_Prerequisite_Subject_Code FOREIGN KEY (Prerequisite_Subject_Code) REFERENCES Subject (Subject_Code)
)
这仍将通过拥有所有正确的键来保持您的引用完整性,但在 1 个主题具有多个先决条件的情况下,查询数据库会变得更加容易。例如
-- WILL RETURN ALL SUBJECTS AVAILABLE GIVEN A CERTAIN PERSONS
-- COMPLETED SUBJECTS.
SELECT DISTINCT s.*
FROM Subject s
INNER JOIN SubjectPrerequisite sp
ON s.Subject_Code = sp.Primary_Subject_Code
WHERE sp.Prerequisite_Subject_Code IN ('C12345', 'C12346')
-- WILL RETURN ALL PRERQUISITE SUBJECTS FOR ANY GIVEN SUBJECT
SELECT s.*
FROM SubjectPrerequisite sp
INNER JOIN Subject s
ON s.Subject_Code = sp.Prerequisite_Subject_Code
WHERE sp.Primary_Subject_Code = 'C34512'