Question

I have a subject table that is recursive because a subject can be a prerequisite of another subject:

  • A subject can have no prerequisites
  • A subject can have 1 prerequisite
  • A subject can have 2 prerequisites

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?

Was it helpful?

Solution 2

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;

An SQLfiddle.

OTHER TIPS

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.

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top