MariaDB Order By子句


在MariaDB資料庫中,ORDER BY子句用於按升序或降序對結果集中的記錄進行排序。

語法:

SELECT expressions  
FROM tables  
[WHERE conditions]  
ORDER BY expression [ ASC | DESC ];

注意:可以對結果進行排序而不使用ASC/DESC屬性。 預設情況下,結果將按升序(ASC)排序。

1. ORDER BY子句不使用ASC/DESC屬性

在這個範例中,使用具有以下資料的students表:

MariaDB [testdb]> select * from students;
+------------+--------------+-----------------+----------------+
| student_id | student_name | student_address | admission_date |
+------------+--------------+-----------------+----------------+
|          1 | Maxsu        | Haikou          | 2017-01-07     |
|          3 | JMaster      | Beijing         | 2016-05-07     |
|          4 | Mahesh       | Guangzhou       | 2016-06-07     |
|          5 | Kobe         | Shanghai        | 2016-02-07     |
|          6 | Blaba        | Shengzhen       | 2016-08-07     |
|          7 | Maxsu        | Sanya           | 2017-08-08     |
+------------+--------------+-----------------+----------------+
6 rows in set (0.00 sec)

範例

SELECT * FROM students  
WHERE student_name LIKE '%Ma%'  
ORDER BY student_id;

執行上面查詢語句,得到以下結果 -

MariaDB [testdb]> SELECT * FROM students
    -> WHERE student_name LIKE '%Ma%'
    -> ORDER BY student_id;
+------------+--------------+-----------------+----------------+
| student_id | student_name | student_address | admission_date |
+------------+--------------+-----------------+----------------+
|          1 | Maxsu        | Haikou          | 2017-01-07     |
|          3 | JMaster      | Beijing         | 2016-05-07     |
|          4 | Mahesh       | Guangzhou       | 2016-06-07     |
|          7 | Maxsu        | Sanya           | 2017-08-08     |
+------------+--------------+-----------------+----------------+
4 rows in set (0.00 sec)

在上面結果集中,可以看到是按student_id欄位從小到大(不指定ASCDESC時,預設使用ASC)來排序的。

2. ORDER BY子句使用DESC屬性

範例

SELECT * FROM students  
WHERE student_name LIKE '%Ma%'  
ORDER BY student_id DESC;

執行上面查詢語句,得到以下結果 -

MariaDB [testdb]> SELECT * FROM students
    -> WHERE student_name LIKE '%Ma%'
    -> ORDER BY student_id DESC;
+------------+--------------+-----------------+----------------+
| student_id | student_name | student_address | admission_date |
+------------+--------------+-----------------+----------------+
|          7 | Maxsu        | Sanya           | 2017-08-08     |
|          4 | Mahesh       | Guangzhou       | 2016-06-07     |
|          3 | JMaster      | Beijing         | 2016-05-07     |
|          1 | Maxsu        | Haikou          | 2017-01-07     |
+------------+--------------+-----------------+----------------+
4 rows in set (0.00 sec)

在上面結果集中,可以看到是按student_id欄位從大到小(指定DESC)來排序的。

3. 按多列排序

假設students表中有兩個人的名字是:Maxsu,我們希望先按student_name升序排序,在列的值相同時,再按student_id降序排序,參考以下查詢語句 -

SELECT * FROM students  
WHERE student_name LIKE '%Ma%'  
ORDER BY student_name ASC, student_id DESC;

執行上面查詢語句,得到以下結果 -