hive 之 交、并、差 探析

2018-12-26  本文已影响0人  大王叫我来巡老和山

上一篇说到了 join,本篇就简单讲一讲对两个表做交、并、差运算。


并集

union 主要有两种用法:

select id,name from t1 
union select id,name from t2 
union select id,name from t3 order by id;
-- This is wrong
select id,name from t1 
union all select id,name from t2;

-- The right post
select * from (
select id,name from t1 
union all select id,name from t2 
) t;

交集

在 sql 语句中,有 intersect 关键字。那么在hive 语句中,如何实现呢?
可以用 left outer join 或者更高效的left semi join 哦~

如何使用,可以参考我的上一篇文章,join 大法:https://www.jianshu.com/p/aac4a15a50c9

差集

  在 sql 语句中,有 minus 关键字,但是 hive 暂时还不支持,那么问题来了,这回又要怎么办?
  答案还是用 join 啦 ~
  交集 和 差集 加在一起就是 上表的全部内容,那么我们在 left outer join 之后的 where 语句中,把对下表的 key 值判断由 is not null(即下表中该条数据存在,也就是交集) 换成 is null (下表中该条数据为 null ,也就是差集啦)即可~

上一篇 下一篇

猜你喜欢

热点阅读