如何在多列上分配FOREIGN KEY约束?
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'上具有FOREIGN KEY约束,该约束引用父表'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查询,我们可以添加另一个外键约束到字段'cust_unq_id',该字段引用父表'customer2'
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: 0 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 | MUL | NULL | | +--------------+-------------+------+-----+---------+-------+ 5 rows in set (0.06 sec)
从以上结果集可以看出,“orders1”表有两个外键约束,一个在“cust_id”上,另一个在“cust_unq_id”上。
广告