如何在hive中从同一个数据库中获取两个表的不匹配记录?

时间:2017-08-24 10:39:15

标签: hadoop hive

例如:

select username, country from table1
Minus
Select username, country from table2;

上面的减号查询在RDBMS中有效但我希望使用hive获得相同的结果。我们可以在配置单元中使用连接来获得结果吗?如果是这样,如何使用配置单元查询获得正确的结果。

3 个答案:

答案 0 :(得分:1)

Hive 2.3.0(2017年7月17日发布)支持设置操作(除UNION之外的MINUS / EXCEPT / INTERSECT) https://issues.apache.org/jira/browse/HIVE-12764

演示

create table table1 (username string, country string);
create table table2 (username string, country string);

insert into table1 values ('Danny','USA'),('Danny','USA'),('David','UK');
insert into table2 values ('David','UK'),('Michal','France');
select username, country from table1
minus
Select username, country from table2
;
+--------------+-------------+
| _u1.username | _u1.country |
+--------------+-------------+
| Danny        | USA         |
+--------------+-------------+

在较旧的Hive版本中,您可以使用 -

select      username
           ,country

from        (           select 1 tab,username, country from table1
            union all   select 2 tab,username, country from table2
            ) t

group by    username
           ,country

having      count(case when tab = 2 then 1 end) = 0
;
+----------+---------+
| username | country |
+----------+---------+
| Danny    | USA     |
+----------+---------+

答案 1 :(得分:1)

您可以按如下方式使用左连接

select table1.username, table1.country 
from table1 left join table2 
     on table1.username=table2.username and table1.country=table2.country 
where table2.username is NULL and table2.country is NULL;

答案 2 :(得分:0)

是的,因为在蜂巢中负号和不存在通常不起作用,所以我们可以在LEFT JOIN条件以下进行负号运算。

SELECT t1.username, t1.country
FROM
(select username, country from table1) t1
LEFT JOIN 
(Select username, country from table2) t2
ON t1.username =t2.username
AND t1.country =t2.country
WHERE t1.username IS NULL

IMP注意:请不要在联接条件后使用WHERE CLAUSE FOR NULL运算代替AND,这将产生不同的结果。

相关问题