首页 > 解决方案 > “在不存在的地方插入”是否包括在同一插入处插入的记录

问题描述

表 1 - id、姓名、地址、项目、日期、价格、...

表 2 - id、name、item

表 2 不能有重复的行(而表 1 可能有一些)。

通过使用“在不存在的地方插入”,它包含的插入该插入的行是否会插入自身?

insert into table2 (id,name,item)
select id, name, item
from table1
where not exists 
(select 1 from table2 where table2.id=table1.id and table2.name=table1.name and table2.item=table1.item) 

标签: sqlsql-serversql-insertnot-exists

解决方案


不,这可以使用以下方法处理select distinct

insert into table2 (id, name, item)
    select distinct id, name, item
    from table1
    where not exists 
    (select 1 from table2 where table2.id=table1.id and table2.name=table1.name and table2.item=table1.item) ;

推荐阅读