简体   繁体   English

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

[英]Insert into table when one value not exist in another table?

I have two tables, they have a same column id , but table1 has more id s than table2 .我有两个表,它们具有相同的列id ,但table1 idtable2 Now I want to find those id a in table1 but not exist in table2 , and insert them into table2 , and set their value of count as 0.现在我想在table1找到那些id a 但在table2不存在的, insert它们插入table2 ,并将它们的值设置为 0。

I tried the following code but it says syntax error, unexpected IF .我尝试了以下代码,但它说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

You can do this with a single insert . . . select您可以使用单个insert . . . select来完成此操作insert . . . select insert . . . select insert . . . select statement: 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);

I am guessing that you are using MySQL if you are getting an error on if ( if is only allowed in procedure/function/trigger code).如果在if ( if只允许在过程/函数/触发器代码中) 出现错误,我猜你正在使用 MySQL。 But even if if where allowed, the query in exists references table2.id and there is no table2 in the from clause.但是,即使if允许的地方,在查询中exists引用table2.id并没有table2from条款。 So that would be the next error.所以这将是下一个错误。

LEFT JOIN also could be used here 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;

Try this:试试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM