我们可以借助 ALTER TABLE 语句将 PRIMARY KEY 约束应用于现有 MySQL 表的列。
语法
ALTER TABLE table_name MODIFY colum_name datatype PRIMARY KEY;
OR
ALTER TABLE table_name ADD PRIMARY KEY (colum_name);
假设我们有一个名为'Player'的表格,并且我们想要给列'ID'添加PRIMARY KEY约束,那么可以通过ALTER TABLE命令来实现,如下所示:
mysql> DESCRIBE Player;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID | int(11) | YES | | NULL | |
| Name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.04 sec)
mysql> ALTER TABLE Player MODIFY ID INT PRIMARY KEY;
Query OK, 0 rows affected (0.22 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> DESCRIBE Player;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | NULL | |
| Name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.04 sec)
从上面的结果集中可以观察到,MySQL向字段'ID'添加了一个PRIMARY KEY约束。我们也可以使用以下查询语句添加PRIMARY KEY约束:
Alter table Player ADD PRIMARY KEY(ID);