MySQL基础——排序查询

进阶3:排序查询

语法:

select 查询列表			第三步执行
from 表				第一步执行
where 筛选条件			第二步执行
order by 排序列表 asc|desc	第四步执行
特点:
	1、asc代表升序,desc代表降序
	如果不写,默认代表升序
	2、order by子句中支持单个字段、多个字段、表达式、函数、别名排序
	3、order by字句一般放在查询语句的最后面,limit字句除外

案例:查询员工信息,要求工资从高到低排序

SELECT * FROM employees ORDER BY salary DESC;
SELECT * FROM employees ORDER BY salary ;

案例2:查询部门编号》=90的员工信息,按入职日期的先后进行排序{添加筛选条件}

SELECT *
FROM employees
WHERE department_id>=90
ORDER BY hiredate ASC;

案例3:(按表达式排序)按年薪的高低显示员工的信息和年薪

SELECT *,salary*12*(1+IFNULL(commission_pct,0)) 年薪
FROM employees
ORDER BY salary*12*(1+IFNULL(commission_pct,0)) DESC;

案例4:(按别名排序)按年薪的高低显示员工的信息和年薪

SELECT *,salary*12*(1+IFNULL(commission_pct,0)) 年薪
FROM employees
ORDER BY 年薪 DESC;

案例5:(按函数排序)按姓名的长度显示员工的姓名和工资

SELECT LENGTH(last_name) 字节长度,last_name,salary
FROM employees
ORDER BY LENGTH(last_name) DESC;

案例6:(按多个字段排序)查询员工信息,要求先按工资排序,再按员工编号排序

SELECT *
FROM employees
ORDER BY salary ASC,employee_id DESC;

例题

SELECT last_name,department_id,salary*12*(1+IFNULL(commission_pct,0)) 年薪
FROM employees
ORDER BY 年薪 DESC,last_name ASC;

SELECT last_name,salary
FROM employees
WHERE salary NOT BETWEEN 8000 AND 17000
ORDER BY salary DESC; 

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

你可能感兴趣的:(MySQL基础,mysql,sql,数据库)