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

use*_*054 2 hive

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

例子。

Insert into table employee partition (day, location) select distinct name, number,
date,aud_date, day, location from tableB.
Run Code Online (Sandbox Code Playgroud)

如果我尝试从 tableB 插入的记录已存在于员工表中,则应绕过它或将其写入另一个表中。我需要检查员工表中是否已存在的列是姓名、号码、日期、日期、位置。我不想检查 aud_date 因为它会有所不同。

jav*_*dba 5

假设“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 
Run Code Online (Sandbox Code Playgroud)

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

因此,在上面的情况下,我们正在精确搜索第二个表条目丢失的条件 - 因此我们:

  • 从表二中选择永不为空(也称为非空)的列之一。那么:number 是一个始终存在的列吗?如果没有,请选择另一个
  • 指定条件“table1-alias”。“table1-never-null-column”= null。这意味着该记录实际上并不存在于连接条件中 - 因此我们发现该记录仅存在于表 1 中。