ORDER BY 关键字用于对结果集进行排序。
ORDER BY 关键字
ORDER BY
关键字用于对结果集按照一个列或者多个列进行排序。
ORDER BY
关键字默认按照升序
对记录进行排序。如果需要按照降序对记录进行排序
,您可以使用DESC
关键字。
SQL ORDER BY 语法
SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
ORDER BY DESC 示例
演示数据库
在猿变手册教程中,我们将使用 yuanbian 样本数据库。
下面是选自 "articles" 表的数据:
+----+--------------+----------+--------+---------------------+
| id | title | author | a_type | pub_date |
+----+--------------+---------—+--------+---------------------+
| 1 | hadoop简介 | 大猿 | 311 | 2003-01-05 11:23:00 |
| 2 | python元类 | 小猿 | 163 | 2003-01-11 13:00:01 |
| 3 | HTML基础 | 猿大头 | 497 | 2004-03-09 12:00:00 |
| 4 | JavaScript | 猿媛 | 20 | 2005-11-3 17:34:12 |
| 5 | ETL快速入门 | 猿媛 | 3 | 2005-11-7 18:40:00 |
+----+--------------+----------+--------+---------------------+
ORDER BY 实例
升序示例
下面的 SQL 语句从 "articles" 表中选取所有文章,并按照 "a_type" 列排序:
SELECT * FROM articles
ORDER BY a_type;
执行输出结果:
+----+--------------+----------+--------+---------------------+
| id | title | author | a_type | pub_date |
+----+--------------+---------—+--------+---------------------+
| 5 | ETL快速入门 | 猿媛 | 3 | 2005-11-7 18:40:00 |
| 4 | JavaScript | 猿媛 | 20 | 2005-11-3 17:34:12 |
| 2 | python元类 | 小猿 | 163 | 2003-01-11 13:00:01 |
| 1 | hadoop简介 | 大猿 | 311 | 2003-01-05 11:23:00 |
| 3 | HTML基础 | 猿大头 | 497 | 2004-03-09 12:00:00 |
+----+--------------+----------+--------+---------------------+
下面的 SQL 语句从 "Websites" 表中选取所有网站,并按照 "alexa" 列降序排序:
降序示例
SELECT * FROM articles
ORDER BY a_type desc;
执行输出结果:
+----+--------------+----------+--------+---------------------+
| id | title | author | a_type | pub_date |
+----+--------------+---------—+--------+---------------------+
| 3 | HTML基础 | 猿大头 | 497 | 2004-03-09 12:00:00 |
| 1 | hadoop简介 | 大猿 | 311 | 2003-01-05 11:23:00 |
| 2 | python元类 | 小猿 | 163 | 2003-01-11 13:00:01 |
| 4 | JavaScript | 猿媛 | 20 | 2005-11-3 17:34:12 |
| 5 | ETL快速入门 | 猿媛 | 3 | 2005-11-7 18:40:00 |
+----+--------------+----------+--------+---------------------+
ORDER BY 多列
下面的 SQL 语句从 "articles" 表中选取所有文章,并按照 "id" 和 "pub_date" 列排序:
SELECT * FROM articles
ORDER BY id, pub_date;
执行输出结果:
+----+--------------+----------+--------+---------------------+
| id | title | author | a_type | pub_date |
+----+--------------+---------—+--------+---------------------+
| 1 | hadoop简介 | 大猿 | 311 | 2003-01-05 11:23:00 |
| 2 | python元类 | 小猿 | 163 | 2003-01-11 13:00:01 |
| 3 | HTML基础 | 猿大头 | 497 | 2004-03-09 12:00:00 |
| 4 | JavaScript | 猿媛 | 20 | 2005-11-3 17:34:12 |
| 5 | ETL快速入门 | 猿媛 | 3 | 2005-11-7 18:40:00 |
+----+--------------+----------+--------+---------------------+
讨论区