我有一个递归的subject
表,因为主题可能是另一个主题的先决条件:
由于有两个先决条件的主题,我将prerequisite_1
和prerequisite_2
列FK指向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?
答案 0 :(得分: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)
)
这允许任意数量的先决条件。
答案 1 :(得分: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;
答案 2 :(得分: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;