在MariaDB資料庫中,ORDER BY
子句用於按升序或降序對結果集中的記錄進行排序。
語法:
SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
注意:可以對結果進行排序而不使用
ASC/DESC
屬性。 預設情況下,結果將按升序(ASC
)排序。
在這個範例中,使用具有以下資料的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
欄位從小到大(不指定ASC
或DESC
時,預設使用ASC
)來排序的。
範例
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
)來排序的。
假設students
表中有兩個人的名字是:Maxsu
,我們希望先按student_name
升序排序,在列的值相同時,再按student_id
降序排序,參考以下查詢語句 -
SELECT * FROM students
WHERE student_name LIKE '%Ma%'
ORDER BY student_name ASC, student_id DESC;
執行上面查詢語句,得到以下結果 -