How can we assign FOREIGN KEY constraint on multiple columns?

MySQLMySQLi Database

MySQL allows us to add a FOREIGN KEY constraint on multiple columns 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.

raja
Published on 19-Feb-2018 10:50:36
Advertisements