MySQL基础005 --- DQL语言之排序查询

排序查询

# 进阶3: 排序查询

/*
引入: 
		 select * from employees;
		 
语法:
		select 查询列表
		from 表
		【where 筛选条件】
		order by 排序列表【asc||desc】

特点:
		1.asc代表的是升序,desc代表的是降序
		2.如果不写,默认是asc升序
*/
# 案例1:查询员工信息,要求工资从高到低排序

SELECT
		*
FROM
		employees
ORDER BY
		salary DESC;
		
#案例2: 查询部门编号>=90的员工信息,按入职时间的先后顺序进行排序【添加筛选条件】

SELECT
		*
FROM
		employees
WHERE
		department_id >=90
ORDER BY
		hiredate ASC;
		
#案例3: 按年薪的高低显示员工的信息和年薪【按表达式排序】

SELECT 
		*,
		salary * 12 * (1+IFNULL(commission_pct,0))
AS
		年薪
FROM
		employees
ORDER BY
		salary * 12 * (1+IFNULL(commission_pct,0)) DESC;
		
#案例4: 按年薪的高低显示员工的信息和年薪【按别名排序】

SELECT 
		*,
		salary * 12 * (1+IFNULL(commission_pct,0))
AS
		年薪
FROM
		employees
ORDER BY
		年薪 DESC;
		
# 案例5:按姓名的长度显示员工的姓名和工资【按函数排序】
SELECT LENGTH(‘john‘);

SELECT 
		LENGTH(last_name) 
AS 
		字节长度,
		last_name,
		salary
FROM
		employees
ORDER BY
		字节长度  DESC;
		
# 案例6: 查询员工信息,要求先按工资升序,再按员工编号降序【按多个字段排序】
SELECT  *
FROM 	employees
ORDER BY salary  ASC, employee_id DESC;

案例1: 查询员工的姓名和部门号和年薪,按年薪降序 按姓名升序

SELECT 
CONCAT(`first_name`,‘   ‘,`last_name`) AS 姓名,
 department_id,
 salary*12*(1+IFNULL(commission_pct,0)) AS 年薪
 FROM
 employees
 ORDER BY 
 年薪 DESC, 姓名 ASC;

案例2: 选择工资不在 8000 到 17000 的员工的姓名和工资,按工资降序

SELECT
CONCAT(first_name,‘   ‘,last_name) AS 姓名,
salary
FROM
employees
WHERE
salary NOT BETWEEN 8000 AND 17000;
ORDER BY 
salary DESC;

案例3: 查询邮箱中包含 e 的员工信息,并先按邮箱的字节数降序,再按部门号升序

SELECT
*,LENGTH(email)
FROM
employees
WHERE
email LIKE ‘%e%‘
ORDER BY 
LENGTH(email) DESC, department_id ASC;	

MySQL基础005 --- DQL语言之排序查询

上一篇:《MySQL数据库》MySQL 优化SQL(explain)


下一篇:定时导出Oracle数据表到文本文件的方法