1

我有一个subject递归表,因为一个主题可以是另一个主题的先决条件:

  • 主题可以没有先决条件
  • 一个主题可以有 1 个先决条件
  • 一个主题可以有2个先决条件

由于有 2 个先决条件的科目,我将prerequisite_1prerequisite_2列 FKs 指向该subject_code列:

CREATE TABLE subject(
    subject_code CHAR(7),
    subject_desc VARCHAR(255) NOT NULL,
    no_of_units TINYINT UNSIGNED NOT NULL CHECK(no_of_units >= 0 AND no_of_units < 13),
    prerequisite_1 CHAR(7),
    prerequisite_2 CHAR(7),
    PRIMARY KEY(subject_code),
    FOREIGN KEY(prerequisite_1, prerequisite_2) REFERENCES subject(subject_code)
)ENGINE=INNODB;

我在 SQL Fiddle 上尝试了代码,但没有创建表。

如何创建一个包含 1 个 PK 列和 2 个 FK 列指向表自己的 PK 的递归表?

4

3 回答 3

1

不要将先决条件放在subject表中,而是使用多对多关系表:

CREATE TABLE prerequisite (
    subject_code CHAR(7),
    prerequisite CHAR(7),
    PRIMARY KEY (subject_code, prerequisite),
    FOREIGN KEY (subject_code) REFERENCES subject(subject_code),
    FOREIGN KEY (prerequisite) REFERENCES subject(subject_code)
)

这允许任意数量的先决条件。

于 2013-07-30T16:30:37.297 回答
0

您需要将它们分成两个单独的外键,并且您可能应该(但不必)命名它们;

CREATE TABLE subject(
    subject_code CHAR(7),
    subject_desc VARCHAR(255) NOT NULL,
    no_of_units TINYINT UNSIGNED NOT NULL 
       CHECK(no_of_units >= 0 AND no_of_units < 13),
    prerequisite_1 CHAR(7),
    prerequisite_2 CHAR(7),
    PRIMARY KEY(subject_code),
    FOREIGN KEY fk_pr1(prerequisite_1) REFERENCES subject(subject_code),
    FOREIGN KEY fk_pr2(prerequisite_2) REFERENCES subject(subject_code)
) ENGINE=INNODB;

一个 SQLfiddle

于 2013-07-30T15:15:10.163 回答
0

所以,这是我的评论:

我相信您的语法错误,请尝试将foreign key每个外键的内容更改为:

CREATE TABLE subject(
    .........

    CONSTRAINT `subject_ibfk_1` FOREIGN KEY (`prerequisite_1`) REFERENCES `subject` (`subject_code`),

    CONSTRAINT `subject_ibfk_2` FOREIGN KEY (`prerequisite_2`) REFERENCES `subject` (`subject_code`)

)ENGINE=INNODB;
于 2013-07-30T15:20:34.747 回答