问题
I was trying to see whether I can use one of the columns in a composite key as a foreign key. And I got strange result.
CREATE TABLE TESTPARENT(
PK1 INT,
PK2 INT,
PRIMARY KEY(PK1,PK2)
);
Query OK, 0 rows affected (0.01 sec)
CREATE TABLE TESTCHILD1(
FK1 INT,
FOREIGN KEY (FK1) REFERENCES TESTPARENT(PK1)
);
Query OK, 0 rows affected (0.01 sec)
CREATE TABLE TESTCHILD2(
FK2 INT,
FOREIGN KEY (FK2) REFERENCES TESTPARENT(PK2)
);
ERROR 1005 (HY000): Can't create table 'test.TESTCHILD2' (errno: 150)
MySQL allows to create a foreign key that reference only the first column in the primary key, but not the second column. Is this strange? Or am I being stupid!
回答1:
As MySQL documentation on foreign keys indicates:
InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.
NDB requires an explicit unique key (or primary key) on any column referenced as a foreign key.
So, if you use innodb, then MySQL does not allow you to create a foreign key on a field that is not the leftmost field in an index.
The reason is that in a multi-column index you cannot look up a value based on a field that is not the left most, therefore the index cannot be used to quickly look up the value for a foreign key check.
This behaviour of MySQL indexes is described in the MySQL documentation on multi-column indexes:
MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index.
回答2:
In FK relations columns on child and parent tables should be indexed. MySQL can not use index on the second column (PK2 in your case). So you need to add index on PK2:
alter table TESTPARENT add key (PK2);
来源:https://stackoverflow.com/questions/38094819/using-one-of-the-columns-in-a-composite-key-as-a-foreign-key