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

Sắp xếp theo một phần của chuỗi trong MySQL (ORDER BY SUBSTRING)

Sử dụng hàm SUBSTRING() (hoặc SUBSTR()) trong mệnh đề ORDER BY để sắp xếp dựa trên đoạn con của chuỗi.

Ví dụ

Tạo bảng chứa ID có tiền tố 'USER_':

mysql> create table DemoTable (UserId varchar(200)); 
Query OK, 0 rows affected (0.68 sec)
mysql> insert into DemoTable values('USER_1234'); 
Query OK, 1 row affected (0.13 sec) 
mysql> insert into DemoTable values('USER_John'); 
Query OK, 1 row affected (0.19 sec) 
mysql> insert into DemoTable values('USER_Sam'); 
Query OK, 1 row affected (0.22 sec) 
mysql> insert into DemoTable values('USER_Carol'); 
Query OK, 1 row affected (0.16 sec) 
mysql> insert into DemoTable values('USER_Bob'); 
Query OK, 1 row affected (0.14 sec)

Dữ liệu gốc:

+------------+
| UserId     |
+------------+
| USER_1234  |
| USER_John  |
| USER_Sam   |
| USER_Carol |
| USER_Bob   |
+------------+

Trường hợp 1: Sắp xếp tăng dần (ASC) từ ký tự thứ 5

mysql> select *from DemoTable order by substring(UserId,5) asc;
+------------+
| UserId     |
+------------+
| USER_1234  |
| USER_Bob   |
| USER_Carol |
| USER_John  |
| USER_Sam   |
+------------+

Trường hợp 2: Sắp xếp giảm dần (DESC)

mysql> select *from DemoTable order by substring(UserId,5) desc;
+------------+
| UserId     |
+------------+
| USER_Sam   |
| USER_John  |
| USER_Carol |
| USER_Bob   |
| USER_1234  |
+------------+

Lưu ý: SUBSTRING(str, pos) bắt đầu từ vị trí pos (1-based). Ví dụ trên bỏ qua 4 ký tự 'USER' (vị trí 5 trở đi).