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)