如何在Hive中使用NOT IN

use*_*344 7 hadoop hive bigdata

假设我有2个表,如下所示.现在,如果我想获得sql将使用的结果,insert into B where id not in(select id from A)3 George在表B中插入.

如何在蜂巢中实现这一点?

表A.

id  name      
1   Rahul     
2   Keshav    
3   George
Run Code Online (Sandbox Code Playgroud)

表B.

id  name      
1   Rahul     
2   Keshav    
4   Yogesh   
Run Code Online (Sandbox Code Playgroud)

Dav*_*itz 11

由于Hive 0.13于2014年4月21日发布3年多以前,因此支持 WHERE子句中的NOT IN与不相关的子查询.

select * from A where id not in (select id from B where id is not null);
Run Code Online (Sandbox Code Playgroud)
+----+--------+
| id |  name  |
+----+--------+
|  3 | George |
+----+--------+
Run Code Online (Sandbox Code Playgroud)

在早期版本中,外表的列应使用表名/别名进行限定.

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.
Run Code Online (Sandbox Code Playgroud)
hive> select * from A where A.id not in (select id from B where id is not null);
OK
3   George
Run Code Online (Sandbox Code Playgroud)

Ps
使用NOT IN时,您应该添加is not null到内部查询,除非您100%确定相关列不包含空值.
一个空值足以导致查询不返回任何结果.

  • @Amir,SQL标准将`x not in(a,b,c)`视为`x <> a,x <> b和x <> c`.如果例如c为NULL,那么`x <> c`是UNKNOWN,因此整个表达式是UNKNOWN.UNKNOWN被视为FALSE.这意味着无论`x`值是什么,查询都不会返回任何行. (5认同)