首页 > 解决方案 > 在 table1 中选择不在 table2 中的值,然后将这些值插入到 table2 中会产生 PRIMARY KEY 约束错误?

问题描述

我想根据 id 匹配从一个表中选择不在另一个表中的行,然后将这些行插入到另一个表中,因为它没有它们。我正在使用这个查询

insert into table2 (key1, key2, key3, some_value1, some_value2)
select t1.key1, t1.key2, t1.key3, some_value1, some_value2
from table1 t1 left join table2 t2
    on t2.key1 = t1.key1 and t2.key2 = t1.key2 and t2.key3 = t1.key3

也试过这个

insert into table2 (key1, key2, key3, some_value1, some_value2)
select t1.key1, t1.key2, t1.key3, some_value1, some_value2
from table1 t1
where not exists (
    select 1
    from table2 t2
    where t2.key1 = t1.key1 and t2.key2 = t1.key2 and t2.key3 = t1.key3
)

当我运行查询时,它给了我一个错误

违反 PRIMARY KEY 约束“PK_table2”。无法在对象“table2”中插入重复键。重复键值为 (101278694, 0060, 4PF93LA#ABM)。

但我不明白,因为我选择了不在 table2 中的值,但它表明我正在尝试将重复值插入 table2

key1, key2, 和key3是 中的主键table2,但是是 中的常规列table1

标签: sqlsql-server

解决方案


表 1 中必须有不止一行具有值 (101278694, 0060, 4PF93LA#ABM)。您的查询需要一些逻辑来解决重复项。你可以做这样的事情

select t1.key1, t1.key2, t1.key3, max(some_value1), max(some_value2)....
(add group by key1,key2,key3)

但也许 max 不是你想要的。你也可以做这样的事情,它只提取不存在于 t2 中且未与 t1 中的多个 value1、value2 组合配对的不同键集

insert into table2 (key1, key2, key3, some_value1, some_value2)
select distinct t1.key1, t1.key2, t1.key3, some_value1, some_value2
from table1 t1
where not exists (
    select 1
    from table1 t3
    where t3.key1 = t1.key1 and t3.key2 = t1.key2 and t3.key3 = t1.key3 and
         (t3.value1 != t1.value1 or t3.value2 != t1.value2)
) and not exists (
    select 1
    from table2 t2
    where t2.key1 = t1.key1 and t2.key2 = t1.key2 and t2.key3 = t1.key3
)

推荐阅读