ALTER TABLE在MySQL中添加复合主键?

要添加复合主键,请使用ALTER命令。让我们首先创建一个演示表

查询创建表。

mysql> create table CompositePrimaryKey
   -> (
   -> Id int,
   -> StudentName varchar(100),
   -> Age int
   -> );

到目前为止,尚未添加复合主键。现在让我们借助desc命令进行检查。

mysql> desc CompositePrimaryKey;

以下是输出。

+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id          | int(11)      | YES  |     | NULL    |       |
| StudentName | varchar(100) | YES  |     | NULL    |       |
| Age         | int(11)      | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.09 sec)

查看上面的示例输出,没有主关键字。这本身表明没有组合主键可用。

现在,让我们使用ALTER命令添加复合主键。查询如下。

mysql>  ALTER table CompositePrimaryKey add primary key(Id,StudentName);
Records: 0  Duplicates: 0  Warnings: 0

上面,我添加了带有列名“ Id”和“ StudentName”的复合主键。要进行相同的检查,我们可以使用DESC命令。查询如下。

mysql> DESC CompositePrimaryKey;

这是输出。

+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id          | int(11)      | NO   | PRI | NULL    |       |
| StudentName | varchar(100) | NO   | PRI | NULL    |       |
| Age         | int(11)      | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

从上面的输出中可以看到,“ PR”表示我们已成功在列Id和StudentName上添加了复合主键。