Tạo bảng demo
mysql> create table DemoTable (
-> FirstName varchar(20),
-> LastName varchar(20)
-> );
Query OK, 0 rows affected (1.44 sec)
Chèn dữ liệu
mysql> insert into DemoTable values('John', 'Smith');
Query OK, 1 row affected (0.35 sec)
mysql> insert into DemoTable values('Chris', 'Brown');
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable values('Carol', 'Taylor');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David', 'Miller');
Query OK, 1 row affected (0.24 sec)
Hiển thị dữ liệu gốc
mysql> select * from DemoTable;
Kết quả
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | John | Smith | | Chris | Brown | | Carol | Taylor | | David | Miller | +-----------+----------+ 4 rows in set (0.00 sec)
Truy vấn sắp xếp theo FirstName, sau đó LastName
mysql> select * from DemoTable order by FirstName, LastName
Kết quả - Sắp xếp A-Z theo FirstName, cùng FirstName thì theo LastName
+-----------+----------+ | FirstName | LastName | +-----------+----------+ | Carol | Taylor | | Chris | Brown | | David | Miller | | John | Smith | +-----------+----------+ 4 rows in set (0.24 sec)
Quy tắc sắp xếp đa cột:
- Sắp xếp theo cột đầu tiên (
FirstName). - Nếu giá trị cột đầu tiên bằng nhau, sắp xếp theo cột thứ hai (
LastName). - Tiếp tục với cột thứ ba, thứ tư... nếu có.
Kết hợp ASC/DESC: ORDER BY FirstName ASC, LastName DESC (mặc định là ASC).
Tối ưu: Tạo composite index (FirstName, LastName) để tăng tốc ORDER BY.