当一个值在另一张表中不存在时插入到表中?

5
我有两个表格,它们都有一个名为id的相同列,但是table1中的idtable2多。现在我想要找到那些在table1中存在但在table2中不存在的id,并将它们插入table2中,并将它们的计数值设置为0。
我尝试了以下代码,但它提示syntax error, unexpected IF
if not exists(select * from table1 where table1.id = table2.id)
begin
    insert into table2 (id, count) values (table1.id, 0)
end
3个回答

12
您可以使用单个insert . . . select语句完成此操作:
insert into table2(id, count)
    select id, 0
    from table1 t1
    where not exists (select 1 from table2 t2 where t2.id = t1.id);

如果您在if上遇到错误,我猜测您正在使用MySQL(因为if仅允许在存储过程/函数/触发器代码中使用)。但是即使if被允许,exists查询中的引用table2.id,而在from子句中没有table2,这将是下一个错误。


2

这里也可以使用LEFT JOIN。

insert into table2(id, count)
select t1.id, 0
from table1 t1 left join table2 t2
on t1.id = t2.id
where t2.id is null;

我认为这是正确的方式! - consigliere

0

试试这个:

INSERT INTO table2 (id,count)
SELECT id,0 from table1 where id NOT IN (select id from table2)

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