How can we add FOREIGN KEY constraints to more than one fields of a MySQL table?


MySQL allows us to add a FOREIGN KEY constraint on more than one field in a table. The condition is that each Foreign Key in the child table must refer to the different parent table.

Example

Suppose we have a table ‘customer2’ which have a Primary Key constraint on the field ‘cust_unq_id’ as follows −

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)

And we have a table orders1 which is already having a Foreign Key constraint on field ‘Cust_id’ referencing to the parent table ‘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)

Now, with the help of following ALTER TABLE query we can add another foreign key constraint on the field ‘cust_unq_id’ referencing to the parent table ‘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)

From the above result set, it can be observed that ‘orders1’ table is having two, one on ‘cust_id’ and other on ‘cust_unq_id’ foreign key constraints.

Updated on: 19-Jun-2020

714 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements