8、mysql資料庫多表查詢(資料並集、內連線、左連結、右連結、全連線)
阿新 • • 發佈:2018-12-11
目錄
場景1:得到 “AB交集後和A“ 的並集 (得到A的所有資料+滿足某一條件的B的資料)
場景2:得到A減去AB的交集 (A中所有資料減去同時滿足B某一條件的資料)
場景1:得到“AB交集後和B“的並集,(場景B的所有資料以及滿足某一條件A的資料)
場景2:得到B減去AB的交集。(B中所有的資料減去與A滿足同一條件的資料)
場景2:AB的並集減去AB的交集,也就是A,B中不滿足某一條件的記錄之和
資料基礎:A和B資料集
1 內連線
場景:A和B資料 的交集
語法: inner join 或者 join
案例:
select a.*,b.* from table_a
inner join table_b
on a.id = b.id
2 左連結
場景1:得到 “AB交集後和A“ 的並集 (得到A的所有資料+滿足某一條件的B的資料)
語法: left join 或者 left outer join
案例:
select a.*,b.* from teablea_a left join teableb_b on a.id=b,id
場景2:得到A減去AB的交集 (A中所有資料減去同時滿足B某一條件的資料)
語法: left join 或者 left outer join 或者 left join + where b.column is null
案例:
select a.id aid,a.age,b.id bid,b.name from teable a
left join teable b
on a.id=b.id
where b.id is null
3 右連結
場景1:得到“AB交集後和B“的並集,(場景B的所有資料以及滿足某一條件A的資料)
語法: right join 或者 right outer join
select a.id aid,a.age,b.id bid,b.name from teable a
right join teable b
on a.id=b.id
場景2:得到B減去AB的交集。(B中所有的資料減去與A滿足同一條件的資料)
語法:right join 或者 right outer join + where a.column is null
select a.id aid,a.age,b.id bid,b.name from table a
right join table b
on a.id = b.id
where a.id is null
4 全連線
場景1:得到A和B的並集 (A、B所有的記錄)
語法: left join union right join
案例:
select a.id aid,a.age,b.id bid,b.name from teableaa
left join teable b
on a.id =b.id
union
select a.id aid,a.age,b.id bid,b.name from teable a
right join teable b
on a.id =b.id
場景2:AB的並集減去AB的交集,也就是A,B中不滿足某一條件的記錄之和
語法:left join + is null union right join + isnull
案例:
select a.id aid,a.age,b.id bid,b.name from table a
left join table b
on a.id = b.id
where b.id is null
union
select a.id aid,a.age,b.id bid,b.name from table a
right join table b
on a.id = b.id
where a.id is null
詳細圖見:https://blog.csdn.net/jintao_ma/article/details/51260458