在 MySQL 中删除一行并使用正确的 ID 重新排序其他行?
mysqlmysqli database
为了理解这个概念,让我们首先创建一个表。创建表的查询如下
mysql> create table ReorderSortDemo -> ( -> UserId int -> ); Query OK, 0 rows affected (0.57 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
mysql> insert into ReorderSortDemo values(14); Query OK, 1 row affected (0.13 sec) mysql> insert into ReorderSortDemo values(4); Query OK, 1 row affected (0.10 sec) mysql> insert into ReorderSortDemo values(6); Query OK, 1 row affected (0.11 sec) mysql> insert into ReorderSortDemo values(3); Query OK, 1 row affected (0.09 sec) mysql> insert into ReorderSortDemo values(8); Query OK, 1 row affected (0.11 sec) mysql> insert into ReorderSortDemo values(18); Query OK, 1 row affected (0.08 sec) mysql> insert into ReorderSortDemo values(1); Query OK, 1 row affected (0.12 sec) mysql> insert into ReorderSortDemo values(11); Query OK, 1 row affected (0.08 sec) mysql> insert into ReorderSortDemo values(16); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from ReorderSortDemo;
以下是输出 −
+--------+ | UserId | +--------+ | 14 | | 4 | | 6 | | 3 | | 8 | | 18 | | 1 | | 11 | | 16 | +--------+ 9 rows in set (0.00 sec)
首先从表中删除一行,然后使用更新命令对其他行重新排序。查询如下 −
mysql> delete from ReorderSortDemo where UserId=8; Query OK, 1 row affected (0.20 sec)
After deleting, let us check the table records once again. The query is as follows −
mysql> select *from ReorderSortDemo;
输出如下
+--------+ | UserId | +--------+ | 14 | | 4 | | 6 | | 3 | | 18 | | 1 | | 11 | | 16 | +--------+ 8 rows in set (0.00 sec)
这是对其他列进行重新排序的查询
mysql> update ReorderSortDemo -> set UserId=UserId-1 -> where UserId > 8; Query OK, 4 rows affected (0.22 sec) Rows matched: 4 Changed: 4 Warnings: 0
让我们再次检查表记录。查询如下 −
mysql> select *from ReorderSortDemo;
输出如下
+--------+ | UserId | +--------+ | 13 | | 4 | | 6 | | 3 | | 17 | | 1 | | 10 | | 15 | +--------+ 8 rows in set (0.00 sec)