天天看點

圖解SQL的inner join、left join、right join、full outer join、union、union all的差別

sql的join文法有很多,

inner join(等值連接配接) 隻傳回兩個表中聯結字段相等的行,

left join(左聯接) 傳回包括左表中的所有記錄和右表中聯結字段相等的記錄,

right join(右聯接) 傳回包括右表中的所有記錄和左表中聯結字段相等的記錄,

看到一篇圖解文章,非常清楚簡潔的說明了使用join操作後的結果集是什麼格式。

a表

id

name

1

pirate

2

monkey

3

ninja

4

spaghetti

b表

rutabaga

darth vade

select * from tablea inner join tableb on tablea.name = tableb.name

滿足tablea.name = tableb.name的資料共有兩條,即 name=pirate 和 name=ninja ,結果如下

結果集

(tablea.)

(tableb.)

圖解SQL的inner join、left join、right join、full outer join、union、union all的差別

(1)

select * from tablea full outer join tableb on tablea.name = tableb.name 

 tablea.name = tableb.name 的情況,a和b的交集有兩條資料,那麼 full outer join的結果集,

應該是2+2+2=6條,即上面的交集,再加剩下的四條資料,沒有比對,以null補全。

null

圖解SQL的inner join、left join、right join、full outer join、union、union all的差別

可以使用ifnull判斷。

(2)

select * from tablea full outer join tableb on tablea.name = tableb.name

where tablea.id is null or tableb.id is null

添加這個 where 條件,可以排除掉兩表的資料交集。

圖解SQL的inner join、left join、right join、full outer join、union、union all的差別

select * from tablea left outer join tableb on tablea.name = tableb.name

以左表為準,根據 tablea.name = tableb.name 這個條件,右表沒有的資料 null 補全。

圖解SQL的inner join、left join、right join、full outer join、union、union all的差別

select * from tablea left outer join tableb on tablea.name = tableb.name where tableb.id is null

其實就是在上一步的結果集中又做了一次篩選工作。

圖解SQL的inner join、left join、right join、full outer join、union、union all的差別

right outer join 是後面的表為基礎,與left outer join用法類似。這裡不介紹了。

union 操作符用于合并兩個或多個 select 語句的結果集。

請注意,union 内部的 select 語句必須擁有相同數量的列。列也必須擁有相似的資料類型。同時,每條 select 語句中的列的順序必須相同。union 隻選取記錄,而union all會列出所有記錄。

新結果集

(3)注意:

select * from tablea union select * from tableb

還需要注意的是“交差集” cross join,這種join沒有辦法用文式圖表示,

因為其就是把表a和表b的資料進行一個n*m的組合,即笛卡爾積。

表達式如下:

這個笛卡爾乘積會産生 4 x 4 = 16 條記錄,一般來說,很少用到這個文法。

但是我們得小心,如果不是使用嵌套的select語句,一般系統都會産生笛卡爾乘積然再做過濾。當表很大的時候,會極大的影響性能。