使用组合键中的一列作为外键 [英] Using one of the columns in a composite key as a foreign key

查看:167
本文介绍了使用组合键中的一列作为外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图看看是否可以使用组合键中的一列作为外键。我得到了奇怪的结果。

  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)参考文献(PK1)
);

Query OK,0 rows affected(0.01 sec)


CREATE TABLE TESTCHILD2(
FK2 INT,
FOREIGN KEY(FK2)参考TESTPARENT(PK2)
);

错误1005(HY000):无法创建表'test.TESTCHILD2'(errno:150)

MySQL允许创建只引用主键中第一列但不引用第二列的外键。这很奇怪吗?或者我是愚蠢的!

解决方案

doc / refman / 5.7 / en / create-table-foreign-keys.htmlrel =nofollow>外键指示:
$ b


InnoDB允许一个外键引用任何索引列或一组列。但是,在被引用的表中,必须有一个索引,其中被引用的列以相同顺序排列为第一列。



NDB需要在被引用为外键的任何列
上显式唯一键(或主键)。



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

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

MySQL索引的这种行为在
$ b


MySQL不能使用索引如果列不构成索引的最左边的前缀,则执行查找。


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!

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.

这篇关于使用组合键中的一列作为外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆