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

Sắp xếp cột bỏ qua từ cụ thể trong MySQL

Tạo bảng demo

mysql> create table DemoTable (
    -> Name text
    -> );
Query OK, 0 rows affected (1.31 sec)

Chèn dữ liệu có từ "name" cần bỏ qua khi sắp xếp

mysql> insert into DemoTable values('John 7');
Query OK, 1 row affected (0.65 sec)
mysql> insert into DemoTable values('John 6');
Query OK, 1 row affected (0.42 sec)
mysql> insert into DemoTable values('John 9');
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable values('name John 3');
Query OK, 1 row affected (0.24 sec)

Hiển thị dữ liệu gốc

mysql> select * from DemoTable;

Kết quả

+-------------+
| Name        |
+-------------+
| John 7      |
| John 6      |
| John 9      |
| name John 3 |
+-------------+
4 rows in set (0.00 sec)

Truy vấn sắp xếp bỏ qua từ "name "

mysql> select * from DemoTable ORDER BY TRIM(REPLACE(LOWER(Name), 'name ', ''));

Kết quả - "name John 3" được sắp xếp như "John 3"

+-------------+
| Name        |
+-------------+
| name John 3 |
| John 6      |
| John 7      |
| John 9      |
+-------------+
4 rows in set (0.00 sec)

Giải thích:

  • LOWER(Name): Chuyển thành chữ thường để so khớp không phân biệt hoa/thường.
  • REPLACE(..., 'name ', ''): Loại bỏ từ "name " (có khoảng trắng sau).
  • TRIM(): Xóa khoảng trắng thừa ở đầu/cuối.
  • ORDER BY kết quả biểu thức đã xử lý.

Lưu ý: Cách này không sử dụng được index, có thể chậm trên bảng lớn. Cân nhắc thêm cột computed/generated column để lưu giá trị đã chuẩn hóa.