[英]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
id
比table2
。 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
并没有table2
中from
条款。 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.