只有当 table2 中不存在
,然而。table1.id
时,我才想将 table1.id
插入到 table2.t1col
中。 t1col
我想我必须使用:
insert into table2 name (t1col) value (select id from table1)
但我只想在 table2
中不存在 id
的情况下添加。
最佳答案
唯一/索引约束保证值的唯一性。所以,推荐。
不幸的是,违反约束会导致整个insert
失败。所以,你可以这样做:
insert into table2(t1col)
select id
from table1 t1
where not exists (select 1 from table2 t2 where t2.t1col = t1.id);
您还应该有一个唯一的索引/约束以防止将来出现问题。
关于sql - 仅当值不存在时才从 SELECT 插入到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34339403/