在大学数据库中,我有一个主题和先决条件的自引用关系。 意味着主题可以具有0个或更多先决条件。
所以我在主题表中声明了它
subject_code VARCHAR(7) NOT NULL CONSTRAINT subject_pk PRIMARY KEY,
subject_name VARCHAR(50) NOT NULL,
pre_requisite VARCHAR(7) NULL CONSTRAINT unit_pre_code FOREIGN KEY
REFERENCES subject(subject_code),
所以我只是想知道我是否正确地采用这种方式,或者是否应该有另一个表格来处理先决条件。
如果我处于正确的轨道,如何插入具有该主题先决条件的数据? 例如 C ++(C12345)主题是操作系统(C34512)的先决条件。 我仍然是新手,我很难找到SQL的优秀和简单的引用。任何建议都会很棒!
答案 0 :(得分:2)
您的关系是一对多,即1个主题可以有许多先决条件,因此您应该使用另一个表。 e.g。
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个主题具有多个先决条件,则会更容易查询数据库。 e.g。
-- 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'