在 MySQL 中删除所有数据后把主键重置为 1?
要删除数据后把主键重置为 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)
使用插入命令在表中插入一些记录。查询如下 −
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)
使用选择语句显示表中的所有记录。查询如下 −
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)
广告