如何重置mysql中表的主键?

如何重置mysql中表的主键?

重置mysql表的主键意味着将auto_increment属性重置为1。重置mysql表主键的语法如下。

alter table yourTableName auto_increment = 1;

为了理解,让我们创建一张表 –

mysql> create table ResetPrimaryKey
−> (
   −> Id int auto_increment,
   −> PRIMARY KEY(Id)
−> );
Query OK, 0 rows affected (0.59 sec)

将一些记录插入表中。插入记录的查询如下 –

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.18 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.15 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.09 sec)

mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.09 sec)

现在,您可以使用select语句显示所有记录。查询如下 –

mysql> select *from ResetPrimaryKey;

以下是仅显示ID(即主键)的输出:

+----+
| Id |
+----+
| 1  |
| 2  |
| 3  |
| 4  |
+----+
4 rows in set (0.00 sec)

以下是使用alter重置表主键的查询 –

mysql> alter table ResetPrimaryKey auto_increment = 1;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0

查询以检查我们是否成功添加了auto_increment属性:

mysql> desc ResetPrimaryKey;

以下是输出 –

+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| Id    | int(11) | NO   | PRI | NULL    | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.11 sec)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程