SQL语句之排序查询–ORDER BY(order by)
语法
select
查询列表
from
表
(where 筛选条件)
order by
排序列表 [asc:升序,desc降序]
说明:对于格式中的where为什么要用括号括起来,格式中不是要有括号,而是说,order by语句中,前面可以由where条件查询,也可以没有,这是根据业务需求的来的,如果由where条件查询,就按照正常的where格式书写,参考我上一篇的SQL语句之条件查询–WHERE(where)
例:
select
*
from
employees
order by
salary desc;
目的:从employees 表中,按照salary,从高到低排序
例:
select
*
from
employees
where
department_id >= 90
order by
hiredate asc;
目的:从employees 表中,筛选出员部门编号大于90的员工信息,信息从小到大排序。
例:
select
*,
salary*12*(1+IFNULL(commission_pct,0))
from
employees
order by
salary*12*(1+IFNULL(commission_pct,0)) desc;
目的:从employees 表中,根据降序计算出年薪。
IFNULL:表示,如果commission_pct为null,输出0;
order后支持别名
例:
select
*,
salary*12*(1+IFNULL(commission_pct,0)) as 年薪
from
employees
order by
年薪 desc;
目的:从employees 表中,根据降序计算出年薪。
IFNULL:表示,如果commission_pct为null,输出0;
order by后支持函数
例:
select
length(last_name) as 字节长度,
last_name,salary
from
employees
order by
length(last_name) desc;
目的:从employees 表中,根据last_name的长度,降序排序。
多个排序条件
例:
select
*
from
employees
order by
salary asc,
employee_id desc;
目的:从employees 表中,首先根据salary从低到高排序,如果有薪资相同的,让后再根据employee_id 编号从高到低排序。