在MySQL中重置主键
要重置主键,首先使用TRUNCATE表,然后使用ALTERTABLE。让我们首先创建一个表-
mysql> create table DemoTable1929 ( UserId int NOT NULL AUTO_INCREMENT, PRIMARY KEY(UserId) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1929 values(); mysql> insert into DemoTable1929 values(); mysql> insert into DemoTable1929 values();
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1929;
这将产生以下输出-
+--------+ | UserId | +--------+ | 1 | | 2 | | 3 | +--------+ 3 rows in set (0.00 sec)
这是重置主键的查询-
mysql> truncate table DemoTable1929; mysql> alter table DemoTable1929 auto_increment=1; Records: 0 Duplicates: 0 Warnings: 0
现在您可以插入记录,它将从1重置主键值-
mysql> insert into DemoTable1929 values(); mysql> insert into DemoTable1929 values();
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1929;
这将产生以下输出-
+--------+ | UserId | +--------+ | 1 | | 2 | +--------+ 2 rows in set (0.00 sec)