Here are two codes
CREATE TABLE tab1 (
col1 int,
col2 int,
PRIMARY KEY(col1, col2)
);
CREATE TABLE tab2 (
col1 int,
FOREIGN KEY (col1) REFERENCES tab1(col1)
);
CREATE TABLE tab1 (
col1 int,
col2 int,
PRIMARY KEY(col1, col2)
);
CREATE TABLE tab2 (
col1 int,
FOREIGN KEY (col1) REFERENCES tab1(col2) <- difference point (col2 used instead of col1)
);
The first code works but the second doesn't work. There error is as follow:
SQL Error [1822] [HY000]: Failed to add the foreign key constraint. Missing index for constraint 'tab2_ibfk_1' in the referenced table 'tab1'.
But why is it so??
BTW I am clearing the database before executing the second code. So it is not due to some duplicate tables present.
And also this answer says, foreign key cannot reference a column which can contain duplicate values. But in my case, if (1, 1) and (1, 2) are inserted in tab1
, then when col1
in referenced from tab2
, col1
does contain duplicate entries.
I am using Ubuntu 20.04.