1. 程式人生 > >Hive 差集運算

Hive 差集運算

oracl div strong select csdn cond take log 組成

差集定義:一般地,設A,B是兩個集合,由所有屬於A且不屬於B的元素組成的集合,叫做集合A減集合B(或集合A與集合B之差)。

類似地,對於集合A,B,我們把集合{x/x∈A,且x¢B}叫做A與B的差集,記作A-B記作A-B(或A\B);

即A-B={x|x∈A,且x ¢B}(或A\B={x|x∈A,且x ¢B} B-A={x/x∈B且x¢A} 叫做B與A的差集。

比如說有這麽兩個表:

hive> select * from A;
OK
1	2
1	3
2	1
2	3
3	1
Time taken: 0.3 seconds, Fetched: 5 row(s)
hive> select * from B;
OK
1	2
1	4
2	2
2	3
Time taken: 0.086 seconds, Fetched: 4 row(s)

  

要取出A與B的差集(A-B):

1	3
2	1
3	1

  

Hive可不可以用not in?可以,但只能用於單個字段。select * from A where (uid,goods) not in (select uid,goods from B);這個oracle是支持的,但hive不行。

hive> select * from A  where uid not in (select uid from B);
3	1
Time taken: 46.09 seconds, Fetched: 1 row(s)

  

Hive可不可以用not exists?顯然也可以!

hive> select * from A  where not exists (select * from B where A.uid=B.uid and A.goods=B.goods);
1	3
2	1
3	1
Time taken: 12.989 seconds, Fetched: 3 row(s)

  

不過前兩種貌似很費資源,在ODPS裏都有限制,下面來介紹一下hive常用的求差集方法,左(右)連接 left outer join

先看一下左連接之後表是什麽樣的

hive> select * from A a left outer join B b on a.uid=b.uid and a.goods=b.goods;
1	2	1	2
1	3	NULL	NULL
2	1	NULL	NULL
2	3	2	3
3	1	NULL	NULL
Time taken: 12.735 seconds, Fetched: 5 row(s)

  

現在只要取出B的uid和goods為null的行就可以了

hive> select a.* from A a left outer join B b on a.uid=b.uid and a.goods=b.goods where b.uid is null and b.goods is null;
1	3
2	1
3	1
Time taken: 13.023 seconds, Fetched: 3 row(s)

  

轉自:https://blog.csdn.net/Dr_Guo/article/details/51182626

Hive 差集運算