MySQL - 如何修复由于删除行导致的自增字段从 1,2,3,4,5 变为 1,3,5。现在我们希望它变成 1,2,3
首先让我们创建一个表 -
mysql> create table DemoTable1955 ( UserId int NOT NULL AUTO_INCREMENT , PRIMARY KEY(UserId) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable1955 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1955 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1955 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1955 values(); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1955 values(); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable1955;
这将产生以下输出 -
+--------+ | UserId | +--------+ | 1 | | 2 | | 3 | | 4 | | 5 | +--------+ 5 rows in set (0.00 sec)
以下是从表中删除行的查询 -
mysql> delete from DemoTable1955 where UserId IN(2,4); Query OK, 2 rows affected (0.00 sec)
现在检查表记录 -
mysql> select * from DemoTable1955;
这将产生以下输出 -
+--------+ | UserId | +--------+ | 1 | | 3 | | 5 | +--------+ 3 rows in set (0.00 sec)
以下是修复自增字段(从 1,2,3,4,5 变为 1,3,5)的查询。下面的查询将使列从 1 开始,类似于 1,2,3 -
mysql> update DemoTable1955 set UserId = (@increment_value := @increment_value+ 1) order by UserId; Query OK, 2 rows affected (0.00 sec) Rows matched: 3 Changed: 2 Warnings: 0
让我们再次检查表记录 -
mysql> select * from DemoTable1955;
这将产生以下输出 -
+--------+ | UserId | +--------+ | 1 | | 2 | | 3 | +--------+ 3 rows in set (0.00 sec)
广告