mysql允许我们在表中的多个列上添加foreign key约束。条件是子表中的每个外键必须引用不同的父表。
示例假设我们有一个名为'customer2'的表,该表在字段'cust_unq_id'上有一个主键约束,如下所示-
mysql> describe customer2;+-------------+-------------+------+-----+---------+-------+| field | type | null | key | default | extra |+-------------+-------------+------+-----+---------+-------+| cust_id | int(11) | yes | | null | || first_name | varchar(20) | yes | | null | || last_name | varchar(20) | yes | | null | || city | varchar(10) | yes | | null | || cust_unq_id | int(11) | no | pri | 0 | |+-------------+-------------+------+-----+---------+-------+5 rows in set (0.06 sec)
我们已经有一个名为orders1的表,它已经在字段'cust_id'上有一个外键约束,引用到父表'customer'。
mysql> describe orders1;+--------------+-------------+------+-----+---------+-------+| field | type | null | key | default | extra |+--------------+-------------+------+-----+---------+-------+| order_id | int(11) | no | pri | null | || product_name | varchar(25) | yes | | null | || orderdate | date | yes | | null | || cust_id | int(11) | yes | mul | null | || cust_unq_id | int(11) | yes | | null | |+--------------+-------------+------+-----+---------+-------+5 rows in set (0.04 sec)
现在,借助以下 alter table 查询,我们可以在引用父表“customer2”的字段“cust_unq_id”上添加另一个外键约束
mysql> alter table orders1 add foreign key(cust_unq_id) references customer2(cust_unq_id);query ok, 0 rows affected (0.25 sec)records: 0 duplicates: 0 warnings: 0mysql> describe orders1;+--------------+-------------+------+-----+---------+-------+| field | type | null | key | default | extra |+--------------+-------------+------+-----+---------+-------+| order_id | int(11) | no | pri | null | || product_name | varchar(25) | yes | | null | || orderdate | date | yes | | null | || cust_id | int(11) | yes | mul | null | || cust_unq_id | int(11) | yes | mul | null | |+--------------+-------------+------+-----+---------+-------+5 rows in set (0.06 sec)
从上面的结果集中可以看出,“orders1”表有两个外键约束,一个在“cust_id”上,另一个在“cust_unq_id”外键约束上。
以上就是我们如何在多列上分配 foreign key 约束?的详细内容。