0

在大学数据库中,我有一个主题和先决条件的自引用关系。这意味着一个主题可以有 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 寻找好的和简单的参考。任何建议也会很棒!

4

1 回答 1

2

您的关系是一对多的,即 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' 
于 2012-05-29T11:20:09.330 回答