如何在Hive中使用NOT IN

9
假设我有如下所示的2个表。现在,如果我想要使用SQL语句insert into B where id not in(select id from A)来实现想要的结果,它将会在表B中插入3 George
那么如何在Hive中实现这个功能呢?
表A:
id  name      
1   Rahul     
2   Keshav    
3   George

表B

id  name      
1   Rahul     
2   Keshav    
4   Yogesh   

我认为这个是一个非常好的参考。 - sharp
1
重复:https://dev59.com/rnrZa4cB1Zd3GeqP7dQj - philantrovert
Philantrovert,arcticwhite谢谢,我明白了。正如Philantrovert所说,可以使用左外连接来完成。 - user8167344
@arcticwhite - 这个答案已经过时了。 - David דודו Markovitz
@philantrovert - 这个答案已经过时了。 - David דודו Markovitz
1个回答

15

NOT IN在带有非相关子查询的WHERE子句中自Hive 0.13发布,该版本已于2014年4月21日发布,已超过3年。

select * from A where id not in (select id from B where id is not null);

+----+--------+
| id |  name  |
+----+--------+
|  3 | George |
+----+--------+

在早期版本中,外部表的列应该带有表名/别名限定。
hive> select * from A where id not in (select id from B where id is not null);
FAILED: SemanticException [Error 10249]: Line 1:22 Unsupported SubQuery Expression 'id': Correlating expression cannot contain unqualified column references.

hive> select * from A where A.id not in (select id from B where id is not null);
OK
3   George

附注:
使用NOT IN时,除非你100%确定相关列不包含null值,否则应在内部查询中添加is not null
一个null值足以导致查询返回无结果。


1
嗨 Dudu,你能详细说明一下 is not null 的问题吗? - Amir
6
@Amir,SQL标准将x not in (a,b,c)视为x<>a and x<>b and x<>c。例如,如果c为NULL,则x<>c为未知,因此整个表达式为未知。未知被视为假。这意味着无论x的值是什么,查询都不会返回任何行。 - David דודו Markovitz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接