Hive學習:Hive鏈接JOIN用例詳解

1 準備數據:

1.1 t_1

01	張三
02	李四
03	王五
04	馬六
05	小七
06	二狗

1.2 t_2

01	11
03	33
04	44
06	66
07	77
08	88

1.3 t_3

01	男
02	男
03	女
04	男
05	女
06	女
07	男
08	X

2 建立表:t_1,t_2,t_3

create table if not exists t_1(id string,name string)row format delimited fields terminated by '\t';

create table if not exists t_2(id string,score string)row format delimited fields terminated by '\t';

create table if not exists t_3(id string,sex string)row format delimited fields terminated by '\t';

3 加載數據

load data local inpath '/root/tmp/t_1' into table t_1;
load data local inpath '/root/tmp/t_2' into table t_2;
load data local inpath '/root/tmp/t_3' into table t_3;

4 笛卡爾積:Join

select * from t_1 join t_2;
等價於:
select * from t_1,t_2;

5 等值鏈接:Join ... on(查交集)

select * from t_1 t1 join t_2 t2 on t1.id=t2.id;

圖解原理:
mysql

5 左鏈接: left join ... on ...

左鏈接是顯示左邊的表的全部數據,若是有右邊表的數據與之對應,則顯示;不然顯示nullsql

select * from t_1 t1 left join t_2 t2 on t1.id=t2.id;

圖解原理:
code

6 右鏈接: right join ... on ...

與左鏈接相似,右鏈接是顯示右邊的表的全部數據,若是有左邊表的數據與之對應,則顯示;不然顯示nullorm

select * from t_1 t1 right join t_2 t2 on t1.id=t2.id;

圖解原理:
blog

7 全鏈接:full outer join ... on

至關於t_1和t_2的數據都顯示,若是沒有對應的數據,則顯示Null.string

select * from t_1 t1 full outer join t_2 t2 on t1.id=t2.id;

圖解原理:it

8 左半鏈接:semi join

semi join僅會顯示t_1的數據,即左邊表的數據。效率比左鏈接快,由於它會先拿到t_1的數據,而後在t_2中查找,只要查找到結果立馬就返回t_1的數據。table

select * from t_1 t1 left semi join t_2 t2 on t1.id=t2.id;

圖解原理:form

9 用單次MapReduce實現鏈接:

若是在鏈接中使用了公共鍵,Hive還支持經過一次MapReduce來鏈接多個表。class

select t1.*,t3.sex,t2.score from t_1 t1 join t_3 t3 on t1.id=t3.id join t_2 t2 on t2.id=t1.id;

相關文章
相關標籤/搜索