在 MySQL 中刪除一行並重新排序其他行以獲得正確的 ID?
為了理解這個概念,我們首先建立一個表。建立表的查詢如下
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)
首先從表中刪除一行,然後使用 UPDATE 命令重新排序其他行。如下查詢所示 −
mysql> delete from ReorderSortDemo where UserId=8; Query OK, 1 row affected (0.20 sec)
刪除後,讓我們再次檢查表記錄。如下查詢所示 −
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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP