使用组合键中的其中一列作为外键

Using one of the columns in a composite key as a foreign key

我试图查看是否可以将复合键中的列之一用作外键。我得到了奇怪的结果。

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 允许创建仅引用主键中的第一列而不是第二列的外键。这很奇怪吗?还是我傻!

在 FK 关系中,子表和父表的列应该被索引。 MySQL 不能在第二列上使用索引(在您的情况下为 PK2)。 所以你需要在PK2上添加索引:

alter table TESTPARENT add key (PK2);

作为 MySQL 关于 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.

因此,如果您使用 innodb,那么 MySQL 不允许您在不是索引最左侧字段的字段上创建外键。

原因是在多列索引中不能根据非最左边的字段查找值,因此索引不能用于快速查找外键检查的值。

MySQL 索引的这种行为在 multi-column indexes 的 MySQL 文档中进行了描述:

MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index.