MySQL 排序 ORDER BY

MySQL中的ORDER BY语句用于对查询结果进行排序,可以根据指定的一个或多个列的值进行排序,支持升序和降序排序。

语法格式如下:

SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;

其中,ORDER BY子句的后面可以指定一个或多个需要排序的列,每个列后面可以跟着关键字ASC(升序,默认)或DESC(降序)。

示例:

假设有如下students表:

+----+-------+------+------+---------+
| id | name  | age  | sex  | address |
+----+-------+------+------+---------+
|  1 | Alice |   18 | F    | Beijing |
|  2 | Bob   |   20 | M    | Shanghai|
|  3 | Carol |   19 | F    | Guangzhou|
|  4 | David |   21 | M    | Beijing |
+----+-------+------+------+---------+

如果要按照年龄从小到大排序,可以使用如下语句:

SELECT * FROM students ORDER BY age ASC;

结果:

+----+-------+------+------+---------+
| id | name  | age  | sex  | address |
+----+-------+------+------+---------+
|  1 | Alice |   18 | F    | Beijing |
|  3 | Carol |   19 | F    | Guangzhou|
|  2 | Bob   |   20 | M    | Shanghai|
|  4 | David |   21 | M    | Beijing |
+----+-------+------+------+---------+

如果要按照性别和年龄进行排序,可以使用如下语句:

SELECT * FROM students ORDER BY sex ASC, age DESC;

结果:

+----+-------+------+------+---------+
| id | name  | age  | sex  | address |
+----+-------+------+------+---------+
|  1 | Alice |   18 | F    | Beijing |
|  3 | Carol |   19 | F    | Guangzhou|
|  2 | Bob   |   20 | M    | Shanghai|
|  4 | David |   21 | M    | Beijing |
+----+-------+------+------+---------+

这样就会先按照性别进行升序排序,然后再按照年龄进行降序排序。