排序查询
语法:
select 查询列表 (III)
from 表名 (I)
[where 筛选条件] (II)
order by 排序列表 [asc(升序,可省略)/desc(降序)] (IV)
特点:
1、asc升序,可省略,desc降序,如不写默认升序
2、order by子句中支持 单个字段、多个字段、表达式、函数、别名
3、order by子句一般放在查询语句最后,limit子句除外。
例如:
查询员工信息,要求工资从高到低排序
SELECT * FROM employees ORDER BY salary DESC;
按年薪的高低显示员工的信息和年薪排序
SELECT ,salary12(1+IFNULL(commission_pct,0)) AS 年薪 FROM employees ORDER BY salary12(1+IFNULL(commission_pct,0)) DESC;(按表达式排序)
或者
SELECT ,salary12(1+IFNULL(commission_pct,0)) AS 年薪 FROM employees ORDER BY 年薪 DESC;(按别名排序)
按姓名长度显示员工的姓名和工资
SELECT LENGTH(last_name) AS 字节长度,last_name,salary FROM employees ORDER BY LENGTH(last_name) DESC;(按函数排序)
查询员工信息,要求先按工资升序,再按员工编号降序(按多个字段排序)
SELECT * FROM employees ORDER BY salary ASC, employees DESC;