Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Sắp xếp và tăng giá trị Position theo thứ tự trong MySQL

Sử dụng biến người dùng (user-defined variable) trong UPDATE ... ORDER BY để gán lại giá trị Position tăng dần theo thứ tự sắp xếp.

Ví dụ

Tạo bảng Position ban đầu không đều:

mysql> create table DemoTable ( 
    FirstName varchar(20), 
    Position int 
); 
Query OK, 0 rows affected (0.71 sec)
mysql> insert into DemoTable values('Chris',100); 
mysql> insert into DemoTable values('Robert',120); 
mysql> insert into DemoTable values('David',130);

Dữ liệu: Chris(100), Robert(120), David(130)

Cập nhật Position tăng 10 theo thứ tự Position cũ

mysql> SET @myPosition := 100; 
Query OK, 0 rows affected (0.00 sec) 
mysql> update DemoTable set Position = @myPosition:=@myPosition+10 ORDER BY Position; 
Query OK, 1 row affected (0.17 sec) 
Rows matched: 3  Changed: 1  Warnings: 0

Kết quả:

+-----------+----------+
| FirstName | Position |
+-----------+----------+
| Chris     | 110      |
| Robert    | 120      |
| David     | 130      |
+-----------+----------+

Giải thích: Biến @myPosition tăng 10 sau mỗi hàng theo ORDER BY Position. Chris (Position=100) được cập nhật thành 110. Robert và David giữ nguyên vì giá trị mới tính ra trùng khớp.

Ứng dụng: Tái số thứ tự (re-sequence) cho cột sort_order, display_order.