MySql查詢總結

1.左連接: A   left   join   B   的連接的記錄數與A表的記錄數同
左連接中 on 與where 條件的區別:where 是在left join之後在篩選符合條件的數據
 
2.右連接:A   right   join   B   的連接的記錄數與B表的記錄數同   
 A   left   join   B   等價B   right   join   A
3.內連接:inner join on 兩表匹配的記錄顯示在查詢結果集中等價於where 條件查詢

4.全外連接: FULL OUTER 是JOIN LEFT OUTER 和 RIGHT OUTER中所有行的超集,包含左、右兩個表的全部行,不管另外一邊的表中是否存在與它們匹配的行

5.自連接:join on ,自身連接是指同一個表自己與自己進行連接。這種一元連接通常用於從自反關係(也稱作遞歸關係)中抽取數據。例如人力資源數據庫中僱員與老闆的關係。
下面例子是在機構表中查找本機構和上級機構的信息。
select s.inst_no superior_inst, s.inst_name sup_inst_name, i.inst_no, i.inst_name
from t_institution i
join t_institution s
on i.superior_inst = s.inst_no
結果是:
superior_inst sup_inst_name        inst_no    inst_name
800           廣州市               5801       天河區
800           廣州市               5802       越秀區
800           廣州市               5803       白雲區

實例:統計某時間段客戶各跟蹤狀態,要求沒有客戶跟蹤狀態的變更也需要顯示,track_state客戶跟蹤狀態字典表,customer_history客戶變更歷史記錄表

select ts.name,ts.id,count(tch.new_track_state_id) as counts,
    case when ts.id=1 then 'red'
    when ts.id=2 then 'orange'
    when ts.id=3 then 'yellow'
    when ts.id=4 then 'green'
    when ts.id=5 then 'blue'
    when ts.id=6 then 'purple'
    when ts.id=7 then 'lilac'
   end as color from track_state ts left join (
    select ch.new_track_state_id from  customer_history ch ,(select t.customer_id,max(t.change_time) as change_time from customer_history t where t.change_time between date_format('20160801','%Y%m%d')
    and date_format('20160831','%Y%m%d') group by t.customer_id ) as temp where temp.customer_id=ch.customer_id and temp.change_time=ch.change_time ) as tch
    on tch.new_track_state_id=ts.id and tch.new_track_state_id is not null
    group by ts.id order by ts.id;

發佈了41 篇原創文章 · 獲贊 8 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章