Reputation:
I have a subject
table that is recursive because a subject can be a prerequisite of another subject:
Since there are subjects with 2 prerequisites, I made the prerequisite_1
and the prerequisite_2
columns FKs pointing to the subject_code
column:
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;
I tried the code on SQL Fiddle and the table is not being created.
How do I create a recursive table with 1 PK column and 2 FK columns pointing back to the table's own PK?
Upvotes: 1
Views: 1536
Reputation: 781848
Instead of putting prerequisites in the subject
table, use a many-to-many relation table:
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)
)
This allows an arbitrary number of prerequisites.
Upvotes: 1
Reputation: 3204
So, here is my comment worked out:
I believe your syntax is wrong, try changing the foreign key
stuff for each foreign key into:
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;
Upvotes: 0
Reputation: 181017
You need to split them into two separate foreign keys, and you should probably (but don't have to) name them;
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;
Upvotes: 0