在 MySQL 中删除所有数据后将主键重置为 1?

mysqlmysqli database更新于 2023/11/26 20:51:00

要在删除数据后将主键重置为 1,请使用以下语法

alter table yourTableName AUTO_INCREMENT=1;
truncate table yourTableName;

完成以上两步后,你将获得从1开始的主键。

为了理解上述概念,让我们创建一个表。创建表的查询如下

mysql> create table resettingPrimaryKeyDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY
   -> );
Query OK, 0 rows affected (0.66 sec)

使用 insert 命令在表中插入一些记录。 查询语句如下 −

mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.15 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.08 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.12 sec)

使用 select 语句显示表中的所有记录。查询如下 −

mysql> select *from resettingPrimaryKeyDemo;

以下是输出 −

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

这是将主键重置为 1 的查询

mysql> alter table resettingPrimaryKeyDemo AUTO_INCREMENT=1;
Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> truncate table resettingPrimaryKeyDemo;
Query OK, 0 rows affected (0.89 sec)

从表中检查记录。查询如下 −

mysql> select *from resettingPrimaryKeyDemo;
Empty set (0.00 sec)

使用插入命令从表中插入一些记录。查询如下 −

mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.12 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into resettingPrimaryKeyDemo values();
Query OK, 1 row affected (0.10 sec)

现在检查表主键从1开始。查询如下 −

mysql> select *from resettingPrimaryKeyDemo;

以下是输出 −

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

相关文章