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)
   );

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1955 values();
mysql> insert into DemoTable1955 values();
mysql> insert into DemoTable1955 values();
mysql> insert into DemoTable1955 values();
mysql> insert into DemoTable1955 values();

使用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);

现在检查表记录-

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;
Rows matched: 3  Changed: 2 Warnings: 0

让我们再次检查表记录-

mysql> select * from DemoTable1955;

这将产生以下输出-

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