排序查询
语法:
select 查询字段1
from 表
where 【筛选条件】
order by 要排序字段2 asc升序、desc 降序,要排字段3 asc升序、desc降序
如果不写默认为升序
案例:查询员工信息,要求工资从高到低排序
SELECT
*
FROM
employees
ORDER BY salary DESC;
#案例2:查询部门编号>=90,按入职日期升序的员工信息
SELECT
*
FROM
employees
WHERE
department_id >=90
ORDER BY hiredate ASC;
#案例:按表达式排序,如按年薪高低显示年薪
SELECT
salary*12*(1+IFNULL(commission_pct,0))
FROM
employees
ORDER BY salary*12*(1+IFNULL(commission_pct,0)) DESC;
#案例:将排序字段起别名,再将按别名排序
SELECT
salary*12*(1+IFNULL(commission_pct,0)) AS 年薪
FROM
employees
ORDER BY
年薪 ASC;
#案例:按姓名的长度降序显示员工的姓名和工资(按函数排序)
SELECT LENGTH(‘aaaa‘); #显示长度为4
SELECT
LENGTH(last_name) AS 字节长度,
last_name,
salary
FROM
employees
ORDER BY
LENGTH(last_name) DESC;
#案例:查询员工信息,要求先按工资排序,再按员工编号排序,(按多个字段排序)
SELECT
*
FROM
employees
ORDER BY
salary ASC,employee_id DESC;
原文地址:https://blog.51cto.com/14437184/2435269
时间: 2024-10-08 15:28:29