如何在 MySQL 中一次對多列進行排序?


若要一次對多列排序,可以使用 ORDER BY 子句。以下是語法 −

select yourColumnName1,yourColumnName2,yourColumnName3 from yourTableName
order by yourColumnName2,yourColumnName3;

我們先建立一個表 −

mysql> create table doubleSortDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100),
   -> StudentCountryName varchar(10)
   -> );
Query OK, 0 rows affected (0.71 sec)

下面是使用 insert 命令在表中插入記錄的查詢 −

mysql> insert into doubleSortDemo(StudentName,StudentCountryName)
values('John','AUS');
Query OK, 1 row affected (0.21 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Sam','UK');
Query OK, 1 row affected (0.20 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Bob','US');
Query OK, 1 row affected (0.16 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Carol','UK');
Query OK, 1 row affected (0.32 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName)
values('David','AUS');
Query OK, 1 row affected (0.19 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Larry','UK');
Query OK, 1 row affected (0.15 sec)

下面是使用 select 語句從表中顯示所有記錄的查詢 −

mysql> select * from doubleSortDemo;

這將產生以下輸出 −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 1         | John        | AUS                |
| 2         | Sam         | UK                 |
| 3         | Bob         | US                 |
| 4         | Carol       | UK                 |
| 5         | David       | AUS                |
| 6         | Larry       | UK                 |
+-----------+-------------+--------------------+
6 rows in set (0.00 sec)

以下是執行 MySQL 排序的查詢,涉及到多列,即學生國家和姓名 −

mysql> select StudentId,StudentName,StudentCountryName from doubleSortDemo
   -> order by StudentCountryName,StudentName;

這將產生以下輸出 −

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 5         | David       | AUS                |
| 1         | John        | AUS                |
| 4         | Carol       | UK                 |
| 6         | Larry       | UK                 |
| 2         | Sam         | UK                 |
| 3         | Bob         | US                 |
+-----------+-------------+--------------------+
6 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

102 次瀏覽

開啟您的 職業生涯

完成課程以取得認證

開始
廣告