3. 排序查询
syntax: select 查询列表 from 表名 [where 筛选条件] order by 排序列表 [desc or asc]
执行顺序是: 1.from 2.where 3.select 4.order by
不写默认是升序
asc 是升序 desc 是降序 这个是写在排序列表后边的
instance: select * from employees order by salary desc;
1.按表达式排序(别名也可)
order by salary*12*(1+ifNull(commission_pct, 0)) desc;
select *,salary*12*(1+ifNull(commission_pct, 0)) 年薪 from employees order by salary*12*(ifNull(commission_pct, 0)) desc;
别名也可以的意思就是 上边的这个查询年薪表达式写好了 在order by 后边直接写别名就好,代码表简洁
select *,salary*12*(1+ifNull(commission_pct, 0)) 年薪 from employees order by 年薪 desc; 效果和上边一样
2.按函数排序
length(字符) 返回长度 字符长度是1字节 汉字长度是3字节
select * from employees order by length(phone_number) desc;
3.按多个字段排序
order by salary asc, employee_id desc;
这个是 他们是按照工资升序排列,如果两个人的工资是一样的,那么他们的员工编号是降序。有先后顺序
特点:
- order by 字句中可以支持单个字段、多个字段、表达式、函数、别名
- order by 子句一般是放在查询语句的最后面,limit子句除外
少年易老学难成,一寸光阴不可轻