如何为现有 MySQL 表的多个列设置 PRIMARY KEY?
可以通过使用 ADD 关键字以及 ALTER TABLE 语句来对现有表的多个列设置 PRIMARY KEY 约束。
示例
假设我们有一个表 Room_allotment,如下所示 -
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)
现在我们可以在多个列,‘id’和‘Name’,上添加复合 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)
可以从上述结果集中观察到,PRIMARY KEY 己被添加到多个列上。
广告