(1)SQL 基本查詢

該篇文章主要是對mysql的查漏補缺,該篇包括:mysql

  • 排序和限制
  • 聚合
  • 表聯結
  • 子查詢與聯合

排序和限制

使用關鍵字 order bylimit;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]複製代碼

說明

  • offset_start表示記錄起始偏移值,row_count表示要查詢的記錄行數。默認offset_start=0,因此能夠這麼寫(limit 100,即offset_start=0;row_count=100);
  • limit常常與order by 一塊兒使用進行記錄的分頁顯示;
  • limit屬於MySQL擴展SQL92的語法,在其餘數據庫上並不能通用。

聚合

使用關鍵字聚合函數(sum/count/max/min等)group bywith rolluphaving等。數據庫

select [field1,...,fieldn] fun_name
from tablename
[where where_condition]
[group by field1,...,field2 [with rollup]]
[having where_condition]複製代碼

說明

  • fun_name表示聚合函數,如sum(field)/count(1)/max(field)/min(field);
  • 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


表聯結

使用關鍵詞joinleft joinright joinon排序

select t1.feild1... 
from table1 t1 [left/right] join table2 t2 
     on t1.fieldn = t2.fieldm 
where where_condition複製代碼

說明

  • 錶鏈接分爲內聯結外聯結,他們之間主要區別:內聯結僅選擇兩張表中互相匹配的記錄,而外聯結會包含其餘不匹配的記錄;
  • 外聯結分爲左聯結右聯結;左聯結包含全部左邊表中的記錄甚至右邊表中沒有和它匹配的記錄,右聯結相反。

子查詢與聯合

使用關鍵字in/not in=/!=exists/not existsunionunion allit

# 子查詢形如
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;複製代碼

說明

  • 子查詢能夠轉化爲表聯結;
  • 表聯結在不少狀況下要優於子查詢;
  • union和union all的主要區別是union all 把結果集直接合並在一塊兒,有可能有重複記錄;union 是把union all的結果進行一次distinct,去除重複記錄後的結果。
相關文章
相關標籤/搜索