這幾天參加面試,碰到了很多join題,特此總結下。
總體上,join在mysql和hive中的使用差别不大,但若細究差別還是有的。
I.首先來看看mysql:
1、笛卡兒積(cross join)
在MySQL中,當不指定on的條件時,inner join(或稱join)和cross join(笛卡兒積)的執行效果一樣,都是兩個表的乘積。若指定了on的條件,則inner join的資料就會明顯規律化。可以發現,所有的join中,cross join是最原始最簡單的基本join操作,就好像其他的join都是從cross join上面變化過去的一樣。
2、内連接配接(inner join)
對于inner join:

如上便是,sql是:
select * from table1 inner join table2 on table1.A = table2.B;
3、左連接配接(left join)
左連接配接(left join)也可以稱為left outer join ,但推薦使用left join。
它的sql是:
select * from table1 left join table2 on table1.A = table2.B;
4、右連接配接(right join)
右連接配接(right join)也可以稱為right outer join ,但推薦使用right join。
sql描述:
select * from table1 right join table2 on table1.A = table2.B;
5、去交集的左連接配接
sql描述:
select * from table1 left join table2 on table1.A = table2.B where table2.B is null;
嚴格的,若不想列值為null的出現,可以寫成如下sql,後面的去交集的右連接配接同理
select table1.* from table1 left join table2 on table1.A = table2.B where table2.B is null;
6、去交集的右連接配接
sql描述:
select * from table1 right join table2 on table1.A = table2.B where table1.A is null;
7、全連接配接
在mysql中是沒有全連接配接(full join)的,可以用union來代替。
sql描述:
select * from table1 left join table2 on table1.A = table2.B
union
select * from table1 right join table2 on table1.A = table2.B;
8、全連接配接去交集
sql描述:
select * from table1 left join table2 on table1.A = table2.B where table2.B is null
union
select * from table1 right join table2 on table1.A = table2.B where table1.A is null;
II.再看看hive的join:
1、笛卡兒積(cross join)
傳回兩個表的笛卡兒積,若數量很大時,将造成災難,慎用。
hive sql描述:
select * from table1 cross join table2;
2、内連接配接(join)
在hive中,内連接配接(join)是最簡單的連接配接操作。
hive sql描述:
select * from table1 join table2 on (table1.A = table2.B);
3、左外連接配接(left join)
左連接配接(left join)也可以稱為left outer join ,但推薦使用left join。
hive sql描述:
select * from table1 left join table2 on (table1.A = table2.B);
4、右外連接配接(right join)
右連接配接(right join)也可以稱為right outer join ,但推薦使用right join。
hive sql描述:
select * from table1 right join table2 on (table1.A = table2.B);
5、全外連接配接(full outer join)
即就是兩個連接配接表中的所有行在輸出中都有對應的行,full outer join 也可以寫成 full join。
hive sql描述:
select * from table1 full outer join table2 on (table1.A = table2.B);
6、半連接配接(left semi join)
貼出《Hadoop權威指南》上的一段介紹
可以看出半連接配接主要是想替代in的作用,因為hive不支援in。對于hive的半連接配接,left semi join以關鍵字前面的表為主表,兩個表對on的條件字段做交集,傳回前面表的記錄。仔細對比,就會發現hive的left semi join 其實和mysql的第5個去交集的左連接配接效果一樣,都實作了條件左連接配接,并且去右表的傳回左表記錄。
hive sql描述:
select * from table1 left semi join table2 on (table1.A = table2.B);
III.總說:
因為hive本身就和mysql很像,是以它的join也比較相似。不同的是hive有半連接配接,這主要是分布式計算方面的考慮。