文法:
select 查詢清單 from 表 【where 篩選條件】order by 排序清單 【asc | desc】
特點:
- asc表示升序,不寫時預設為升序。desc表示降序。
- order by子句可以支援 單個字段、多個字段、表達式、函數、别名。
- 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
*,
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 ;
練習:
1、查詢員工的姓名和部門号和年薪,按年薪降序 按姓名升序
SELECT
last_name,
department_id,
salary * 12 * (1+ IFNULL(commission_pct, 0)) 年薪
FROM
employees
ORDER BY 年薪 DESC,
last_name ASC ;
2、選擇工資不在8000到17000的員工的姓名和工資,按工資降序
SELECT
last_name,
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 ;