該篇文章主要是對mysql的查漏補缺,該篇包括:mysql
使用關鍵字 order by
和limit
;sql
//排序
select *
from tablename
[where condition]
[order by field1 [desc/asc],field2 [desc/asc],...,fieldn [desc/asc]]複製代碼
order by
後面能夠跟多個不一樣的排序字段,而且每個排序字段能夠有不一樣的排序順序;\\限制查詢
select ... [limit offset_start,row_count]複製代碼
limit
常常與order by
一塊兒使用進行記錄的分頁顯示;limit
屬於MySQL擴展SQL92的語法,在其餘數據庫上並不能通用。使用關鍵字聚合函數(sum/count/max/min等)
、group by
、with rollup
、having
等。數據庫
select [field1,...,fieldn] fun_name
from tablename
[where where_condition]
[group by field1,...,field2 [with rollup]]
[having where_condition]複製代碼
group by
表示要進行分類聚合的字段;with rollup
,表示對分類聚合的結果進行再彙總;having
表示對分類後的結果再進行條件過濾。例一函數
# 在用戶表上,統計各個部門的人數
select department,count(1)
from users
group by department複製代碼
department | count(1) |
---|---|
人事部 | 5 |
研發部 | 10 |
總裁 | 3 |
例二spa
# 統計各個部門人數,又要統計總人數
select department,count(1)
from users
group by department
with rollup;複製代碼
department | count(1) |
---|---|
人事部 | 5 |
研發部 | 10 |
總裁 | 3 |
null | 18 |
例三code
# 統計人數大於5的部門
select department,count(1)
from users
group by department
having count(1)>5;複製代碼
department | count(1) |
---|---|
研發部 | 10 |
使用關鍵詞join
、left join
、right join
、on
等排序
select t1.feild1...
from table1 t1 [left/right] join table2 t2
on t1.fieldn = t2.fieldm
where where_condition複製代碼
內聯結
和外聯結
,他們之間主要區別:內聯結僅選擇兩張表中互相匹配的記錄,而外聯結會包含其餘不匹配的記錄;左聯結
和右聯結
;左聯結包含全部左邊表中的記錄甚至右邊表中沒有和它匹配的記錄,右聯結相反。使用關鍵字in/not in
、=/!=
、exists/not exists
、union
、union all
。it
# 子查詢形如
select * from table1
where department in(select department
from table2
where where_condition)
#聯合
select * from table1
union [all]
select * from table2
...
union [all]
select * from tablen;複製代碼