DQL + 排序

排序查询

语法:
	select 查询列表
	from 表名
	where 条件
	order by 排序列表 asc|desc;


特点:
1.asc 升序 默认 desc降序
2.排序的列表可以是单个字段、多个字段、函数、表达式、别名或者组合

1. 单个字段排序

 案例1:查询员工的姓名和薪资 并且按薪资降序
 
 select first_name,last_name,salary from employees order by salary desc;
案例2:查询没有奖金的员工的姓名和薪资 并且按照薪资升序

select first_name,last_name,salary from employees where commission_pct is null
order by salary asc;

2.多个字段排序

案例3:查询员工的薪资和姓名, 按照薪资降序,如果薪资相同按照名字排序
select first_name,last_name,salary from employees order by salary desc,last_name asc;

3.表达式 ifnull

案例4:查询姓名中包含e的员工姓名和薪资 并且按照年薪降序

select first_name,last_name,salary,commission_pct,
(salary + ifnull(commission_pct,0)*salary)*12 as 年薪 from employees
where last_name like '%e%'
order by 年薪 desc

4.函数

案例5:查询有奖金的员工的姓名和年薪 并且按照姓名的长度排序

select first_name,last_name,(salary+IFNULL(commission_pct,0))*12 as 年薪 from employees
order by length(last_name) asc,last_name asc;

5.别名

查询员工的姓名和年薪,并且按照年薪排序

select first_name,last_name,salary,commission_pct,
(salary + ifnull(commission_pct,0)*salary)*12 as 年薪 from employees
where last_name like '%e%'
order by 年薪 desc;
原文地址:https://www.cnblogs.com/conglingkaishi/p/15215299.html