Hive中join方法總結--有這一篇就夠了
1. 常見的四種join的區別
常見的join主要有下面四種,join,outer join, semi join和inner join,下面對這四個join的關係進行說明
(1.1)join等價於inner join,也就是隻會將兩表都存在的join在一起
(1.2)outer join分為:
left outer join(等價於left join),right outer join(right join)和full outer join(full join)
Left join是以左表為基準,右表不存在的key均賦值為null
Right join是以右表為基準,左
Full join是取出現在左右兩表的key的並集,某張表裡面不存在的key賦值為null
(1.3)semi join:semi join只有left semi join,不存在semi join 和 right semi join
left semi join跟join的邏輯是一樣的,但是有著三點不同
綜上所述:join語句其實只有五種:join(inner join)、left join(left outer join)、right join(right outer join)、full join(full outer join)、left semi join
2. 對於各種join的使用舉例
我們假設有表tab1和tab2:
tab1: tab2:
stuNo1 stuName1 stuNo2 stuName2
1 a 1 x
2 b 1 y
3 c 2 z
(2.1)join(inner join)就是取交集的關係
select tab1.stuNo1, tab1.stuName1, tab2.stuNo2,tab2.stuName2 from( select * from tab1 ) t1 join ( select * from tab2 ) t2 on t1.stuNo1 = t2.stuN02
結果如下:
stuNo1 stuName1 stuNo2 stuName2
1 a 1 x
1 a 1 y
2 b 2 z
如果沒有on,那麼就會進行笛卡爾積操作,比如tab1有m行,tab2有n行,那麼join之後的結果就會有m*n行。
(2.2)left join
兩表關聯,左表的key全部保留,右表關聯不上的賦值null
select tab1.stuNo1, tab1.stuName1, tab2.stuNo2,tab2.stuName2
from(
select * from tab1
) t1
left join
(
select * from tab2
) t2
on t1.stuNo1 = t2.stuN02
結果如下:
stuNo1 stuName1 stuNo2 stuName2
1 a 1 x
1 a 1 y
2 b 2 z
3 c null null
(2.3)right join同理,不再贅述
(2.4)full join
全表關聯,即是左外連線和右外連線結果集合求並集 ,左右表均可賦值為null。當前例子下跟left join的結果相同。
如果full join不加on過濾條件,計算結果也是笛卡爾積。
(2.5)left semi join
邏輯跟join一樣,只join左右表中同時出現的key。跟join的不同有三點:
(2.5.1)比join高效,因為對於右表中重複出現的行只遍歷一次
(2.5.2)最後 select 的結果只許出現左表的那些列
(2.5.3)JOIN 子句中右邊的表只能在 ON 子句中設定過濾條件,在 WHERE 子句、SELECT 子句或其他地方過濾都不行。舉例如下:
SELECT * FROM table1 LEFT SEMI JOIN table2 on ( table1.student_no =table2.student_no) where table2.student_no>3
上面這樣會報錯,應該寫成:
SELECT * FROM table1 LEFT SEMI JOIN table2 on ( table1.student_no =table2.student_no and table2.student_no>3)
(2.6)其他常用方法
(2.6.1)交集去並集
select * from table1 full outer join table2 on table1.student_no=table2.student_no where table1.student_no is null or table2.student_no is null
(2.6.2)左表獨有
select * from table1 left outer join table2 on table1.student_no=table2.student_no where table2.student_no is null
參考連結: