提问者:小点点

如果一个表中没有值,则在另一个表中插入该值


我有两个表,表1表2。 表1只有一列,比如idtable2除了Id之外还有多个其他列。我需要编写一个配置单元查询,首先检查给定的Id是否存在于table1的Id列中。 如果Id不存在,我需要将其插入table2,否则插入null

例如:

表1

----Id1------
"abcde"
"ghdis"
----------

现在我假设给我一个值“sjsnx”。 查询应该通过table1运行,并在table2中插入“SJSNX”。 如果将“ABCDE”作为值,查询应该在table2中插入null。


共2个答案

匿名用户

如果我理解正确,您可以使用not exists获取表1中的ID,而不是表2中的ID:

insert into table2 (id, . . . )
    select t1.id, . . . 
    from table1 t1
    where not exists (select 1 from table2 t2 where t2.id = t1.id);

。 。。用于其他列及其值。

匿名用户

您需要用某种编程语言(可能是SHELL,Python等)编写代码。 这不能在使用hive时一次性完成,因为您的需求需要执行两次数据库插入。 同样,对于您的输入需求,您可以利用配置单元配置参数使用设置值来搜索ID。

您的代码在Shell中看起来如下所示:

检查第一个表:

 search_id='<your search id>'

 table1search_var=`hive -S -e "select id from table1 where id=${hiveconfig:db_search_id}" --hiveconfig:db_search_id=$search_id`;
 
 if [ -z "$table1search_var" ];
 then
   echo "Found Null row. Hence inserting search id into table2"
   hive -S -e "insert into table2(id) values('$search_id')"
 
 else
   echo "Found Not Null rows. Hence inserting NULL into table2"
   hive -S -e "insert into table2(id) values(null)"
 
 fi

希望这能有所帮助:)