如何在多个列上分配 FOREIGN KEY 约束?
mysqlmysqli database
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 查询,我们可以在字段 ‘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’。