MySQL 如何将主键更改为自增
要将主键更改为自增,可以使用MODIFY命令。让我们先创建一张表。
mysql> create table changePrimaryKeyInAutoIncrement
-> (
-> StudentId int not null primary key,
-> StudentName varchar(100),
-> StudentAge int,
-> StudentAddress varchar(100)
-> );
Query OK, 0 rows affected (0.63 sec)
现在让我们使用desc命令检查表的描述:
mysql> desc changePrimaryKeyInAutoIncrement;
这将产生以下输出
+----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| StudentId | int(11) | NO | PRI | NULL | |
| StudentName | varchar(100) | YES | | NULL | |
| StudentAge | int(11) | YES | | NULL | |
| StudentAddress | varchar(100) | YES | | NULL | |
+----------------+--------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
查看上述示例输出,StudentId列是一个主键。现在让我们将主键更改为自增:
mysql> alter table changePrimaryKeyInAutoIncrement MODIFY StudentId INT AUTO_INCREMENT;
Query OK, 0 rows affected (1.48 sec)
Records: 0 Duplicates: 0 Warnings: 0
让我们再次检查表的描述:
mysql> desc changePrimaryKeyInAutoIncrement;
这将产生以下输出
+----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+----------------+
| StudentId | int(11) | NO | PRI | NULL | auto_increment |
| StudentName | varchar(100) | YES | | NULL | |
| StudentAge | int(11) | YES | | NULL | |
| StudentAddress | varchar(100) | YES | | NULL | |
+----------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
查看上述示例输出,StudentId列已更改为自增。
阅读更多:MySQL 教程
极客教程