在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 | +------------+--------------+-----------------+----------------+ 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 | +------------+--------------+-----------------+----------------+ 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 | +------------+--------------+-----------------+----------------+ 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;
执行上面查询语句,得到以下结果 -