在插入之前查找记录是否已存在于HIVE表中

时间:2014-01-06 21:26:55

标签: hive

我有一个HIVE分区表,在将记录插入其中之前,我需要查找记录是否已经存在。

实施例

Insert into table employee partition (day, location) select distinct name, number,
date,aud_date, day, location from tableB.

如果我试图从tableB插入的记录已经存在于employee表中,它应该绕过或写入另一个表。我需要检查的列是否已存在于employee表中的是名称,编号,日期,日期,位置。我不想检查aud_date,因为它会有所不同。

1 个答案:

答案 0 :(得分:3)

假设“number”列是“not null”列(如果不是这样,请选择另一个列来检查null:

(注意:在OP的后续请求中添加了“where date> =”内联视图)

from (
select distinct e.number as e_number, B.name, B.number, b.date, B.aud_date, 
  B.day, B.location 
from tableB B left outer join
   (select * from employee where date >= <blah>) e
   on e.name=B.name and e.number = e.number 
   and  e.date = B.date and e.day=B.day and e.location=B.location
  where e.number is null
) j 
insert overwrite into table employee e 
select j.name, j.number, j.date, j.aud_date, j.day, j.location 

回答“为什么e.number在那里是空条件”的问题:左外连接确保第一个表中的所有值都包含在结果中。那么当第二个表中没有值时会发生什么:在这种情况下,第二个表中的所有列都报告为null。

因此,在上面的情况中,我们正在精确搜索第二个表项缺失的情况 - 因此我们:

  • 从表二中选择一个永不空(又名非空)列。那么:数字是一个永远存在的列?如果没有,那么请选择另一个
  • 指定条件“table1-alias”。“table1-never-null-column”= null。这意味着记录实际上不存在于连接条件中 - 因此我们发现记录仅存在于表1中。
相关问题