1. 程式人生 > 實用技巧 >【超詳細】MySQL學習筆記彙總(四)

【超詳細】MySQL學習筆記彙總(四)

MySQL學習筆記彙總(四)

五、進階3:排序查詢

select * from employees;
select  
	查詢列表
from  
	表
[where 篩選條件]
order by 
	排序列表 [asc|desc]

支援:
①:表示式
②:別名
③:函式名
④:多個欄位排序
執行順序:

  • 一般放在查詢語句的最後面,但limit字句除外是在最後面
  • from 表-》where 字句-》select 欄位-》order by 字句

案例1:查詢員工資訊,要求工資從高到低排序

select * from employees order by salary asc;#升序
select * from employees order by salary desc;

案例2:查詢部門編號>=員工資訊,按入職時間的先後進行排序

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 sql
  employees
order by 
   姓名長度 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 
	not (salary  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;