MysQL培训课程:Order by查询排序
最新学讯:近期OCP认证正在报名中,因考试人员较多请尽快报名获取最近考试时间,报名费用请联系在线老师,甲骨文官方认证,报名从速!
我要咨询MysQL培训课程:Order by查询排序,使用ORDER BY子句对查询返回的结果按一列或多列排序。ORDER BY子句的语法格式为:
ORDER BY column_name [ASC|DESC] [,…]
其中ASC表示升序,为默认值,DESC为降序。ORDER BY不能按text、text和image数据类型进行排 序。另外,可以根据表达式进行排序。
例如,这里是动物生日,按日期排序:
MySQL> SELECT name, birth FROM pet ORDER BY birth;
+----------+------------+
| name | birth |
+----------+------------+
| Buffy | 1989-05-13 |
| Fang | 1990-08-27 |
| Bowser | 1990-08-31 |
| Fluffy | 1993-02-04 |
| Claws | 1994-03-17 |
| Slim | 1996-04-29 |
| Whistler | 1997-12-09 |
| Chirpy | 1998-09-11 |
| Puffball | 1999-03-30 |
+----------+------------+
为了以逆序排序,增加DESC(下降 )关键字到你正在排序的列名上:
MySQL> SELECT name, birth FROM pet ORDER BY birth DESC;
+----------+------------+
| name | birth |
+----------+------------+
| Puffball | 1999-03-30 |
| Chirpy | 1998-09-11 |
| Whistler | 1997-12-09 |
| Slim | 1996-04-29 |
| Claws | 1994-03-17 |
| Fluffy | 1993-02-04 |
| Bowser | 1990-08-31 |
| Fang | 1990-08-27 |
| Buffy | 1989-05-13 |
+----------+------------+
能在多个列上排序。
例如,按动物的种类排序,然后按生日,首先是动物种类中最年轻的动物,使用下列查询:
MySQL> SELECT name, species, birth FROM pet ORDER BY species, birth DESC;
+----------+---------+------------+
| name | species | birth |
+----------+---------+------------+
| Chirpy | bird | 1998-09-11 |
| Whistler | bird | 1997-12-09 |
| Claws | cat | 1994-03-17 |
| Fluffy | cat | 1993-02-04 |
| Bowser | dog | 1990-08-31 |
| Fang | dog | 1990-08-27 |
| Buffy | dog | 1989-05-13 |
| Puffball | hamster | 1999-03-30 |
| Slim | snake | 1996-04-29 |
+----------+---------+------------+
注意DESC关键词仅适用于紧跟在它之前的列名字(birth);species值仍然以升序被排序。注意,输出首先按照species排序,然后具有相同species的宠物再按照birth降序排列。