排序查询(order by)
语法结构:
select *
from 表
[where 筛选条件]
order by 排序条件[asc/desc]
特点:
1. asc(ascending)代表升序,desc(desending)代表降序,不写默认升序
2. order by子句后可支持单个字段、多个字段、表达式、函数、别名
3. order by子句一般放在查询语句的最后(limit子句除外)
#案例1:查询员工信息,按照工资从高到低排序
SELECT
*
FROM
employees
ORDER BY
salary DESC;
#案例2:查询部门编号大于等于90的员工信息,并按入职时间先后顺序进行排序【添加筛选条件】
SELECT
*
FROM
employees
WHERE
department_id>=90
ORDER BY
hiredate ASC;
#案例3:按年薪的高低显示员工的名字和年薪【按表达式排序】
SELECT
last_name,salary*12*(1+IFNULL(commission_pct,0)) AS 年薪
FROM
employees
ORDER BY
salary*12*(1+IFNULL(commission_pct,0)) DESC;
# 【按别名排序】
SELECT
last_name,salary*12*(1+IFNULL(commission_pct,0)) AS 年薪
FROM
employees
ORDER BY
年薪 DESC;
#案例5:按姓名的长度显示员工的姓名和工资【按函数排序】
SELECT
last_name,salary
FROM
employees
ORDER BY
LENGTH(last_name) ASC;
案例6:查询员工信息,先按工资升序,再按员工编号降序【按多个字段排序】
SELECT
*
FROM
employees
ORDER BY
salary ASC,employee_id DESC;
练习1:选择工资不在8000-17000的员工的姓名和工资,按工资降序
SELECT
last_name,salary
FROM
employees
WHERE
salary NOT BETWEEN 8000 AND 17000
ORDER BY
salary DESC;
练习2:查询邮箱中包含e的员工信息,并先按邮箱的字节数降序,再按部门号升序
SELECT
*
FROM
employees
WHERE
email LIKE "%e%"
ORDER BY
LENGTH(email) DESC,department_id ASC;