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
字段從小到大(不指定ASC
或DESC
時,默認使用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;
執行上面查詢語句,得到以下結果 -