We can set PRIMARY KEY constraints on multiple columns of an existing table by using the ADD keyword and the ALTER TABLE statement.
Suppose we have a table "Room_allotment" as follows -
mysql> Create table Room_allotment(Id Int, Name Varchar(20), RoomNo Int); Query OK, 0 rows affected (0.20 sec) mysql> Describe Room_allotment; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | Id | int(11) | YES | | NULL | | | Name | varchar(20) | YES | | NULL | | | RoomNo | int(11) | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 3 rows in set (0.11 sec)
Now we can add compound on multiple columns "id" and "Name" using the following query Primary key
mysql> Alter Table Room_allotment ADD PRIMARY KEY(Id, Name); Query OK, 0 rows affected (0.29 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> Describe Room_allotment; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | Id | int(11) | NO | PRI | 0 | | | Name | varchar(20) | NO | PRI | | | | RoomNo | int(11) | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 3 rows in set (0.12 sec)
As can be seen from the above result set, PRIMARY KEY has been added to multiple columns.
The above is the detailed content of How can we set PRIMARY KEY on multiple columns of an existing MySQL table?. For more information, please follow other related articles on the PHP Chinese website!