7.ORDER BY 子句
Posted 为尊严而奋斗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了7.ORDER BY 子句相关的知识,希望对你有一定的参考价值。
ORDER BY 语句
ORDER BY 语句用于根据指定的列对结果集进行排序。
ORDER BY 语句默认按照升序对记录进行排序。
如果您希望按照降序对记录进行排序,可以使用 DESC 关键字。
1.以时间显示,升序
mysql> select * from Orders order by OrderDate;
+------+------------+------------+----------+
| O_Id | OrderDate | OrderPrice | Customer |
+------+------------+------------+----------+
| 1 | 2008-07-22 | 1000.00 | Carter |
| 6 | 2008-11-22 | 1000.00 | Adams |
| 5 | 2008-11-29 | 1000.00 | Bush |
| 2 | 2008-12-24 | 1000.00 | Bush |
| 3 | 2008-12-26 | 1000.00 | tom |
| 4 | 2008-12-27 | 1000.00 | Carter |
| 1 | 2008-12-29 | 1000.00 | Bush |
+------+------------+------------+----------+
7 rows in set (0.04 sec)
2.以字母顺序显示Customer名称,并以数字顺序显示顺序号(OrderDate):
mysql> select * from Orders order by Customer,OrderDate;
+------+------------+------------+----------+
| O_Id | OrderDate | OrderPrice | Customer |
+------+------------+------------+----------+
| 6 | 2008-11-22 | 1000.00 | Adams |
| 5 | 2008-11-29 | 1000.00 | Bush |
| 2 | 2008-12-24 | 1000.00 | Bush |
| 1 | 2008-12-29 | 1000.00 | Bush |
| 1 | 2008-07-22 | 1000.00 | Carter |
| 4 | 2008-12-27 | 1000.00 | Carter |
| 3 | 2008-12-26 | 1000.00 | tom |
+------+------------+------------+----------+
7 rows in set (0.00 sec)
3.以逆字母顺序显示Customer名称:
mysql> select * from Orders order by Customer desc ;
+------+------------+------------+----------+
| O_Id | OrderDate | OrderPrice | Customer |
+------+------------+------------+----------+
| 3 | 2008-12-26 | 1000.00 | tom |
| 1 | 2008-07-22 | 1000.00 | Carter |
| 4 | 2008-12-27 | 1000.00 | Carter |
| 1 | 2008-12-29 | 1000.00 | Bush |
| 2 | 2008-12-24 | 1000.00 | Bush |
| 5 | 2008-11-29 | 1000.00 | Bush |
| 6 | 2008-11-22 | 1000.00 | Adams |
+------+------------+------------+----------+
7 rows in set (0.00 sec)
4.以逆字母顺序显示Customer名称,并以数字顺序显示顺序号OrderDate:
mysql> select * from Orders order by Customer desc, OrderDate asc ;
+------+------------+------------+----------+
| O_Id | OrderDate | OrderPrice | Customer |
+------+------------+------------+----------+
| 3 | 2008-12-26 | 1000.00 | tom |
| 1 | 2008-07-22 | 1000.00 | Carter |
| 4 | 2008-12-27 | 1000.00 | Carter |
| 5 | 2008-11-29 | 1000.00 | Bush |
| 2 | 2008-12-24 | 1000.00 | Bush |
| 1 | 2008-12-29 | 1000.00 | Bush |
| 6 | 2008-11-22 | 1000.00 | Adams |
+------+------------+------------+----------+
7 rows in set (0.00 sec)
以上是关于7.ORDER BY 子句的主要内容,如果未能解决你的问题,请参考以下文章
我们如何在具有GROUP BY子句的查询中选择非聚合列,而GROUP BY子句在功能上不依赖于GROUP BY子句中的列?
ORDER BY 子句的表达式 #1 不在 GROUP BY 子句中,并且包含非聚合列