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

Sắp xếp theo giá trị số từ chuỗi như 'CSE 15', 'CSE 11' trong MySQL


Tạo bảng:

mysql> create table DemoTable1969 ( BranchCode varchar(20) ); Query OK, 0 rows affected (0.00 sec)

Thêm dữ liệu:

mysql> insert into DemoTable1969 values('CSE 101'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 11'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 15'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 6'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 201'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 110'); Query OK, 1 row affected (0.00 sec)

Hiển thị dữ liệu gốc (sắp xếp theo chuỗi):

mysql> select * from DemoTable1969;
+------------+
| BranchCode |
+------------+
| CSE 101    |
| CSE 11     |
| CSE 15     |
| CSE 6      |
| CSE 201    |
| CSE 110    |
+------------+
6 rows in set (0.00 sec)

Truy vấn sắp xếp theo phần số sau khoảng trắng, ép kiểu sang số nguyên (SIGNED) giảm dần:

mysql> select * from DemoTable1969 order by CAST(SUBSTRING(BranchCode, LOCATE(' ', BranchCode)+1) AS SIGNED) DESC;

Kết quả sắp xếp đúng theo số:

+------------+
| BranchCode |
+------------+
| CSE 201    |
| CSE 110    |
| CSE 101    |
| CSE 15     |
| CSE 11     |
| CSE 6      |
+------------+
6 rows in set (0.00 sec)