sql - 在 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
解决方案
表 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
)
推荐阅读
- ios - 如何将数据从模型数组中的数组填充到 UITableView?
- ios - 用可用覆盖 open var:
:0: 错误:“xxx”仅适用于 iOS 11.0 或更高版本 - javascript - 我想使用 Javascript 在可编辑控件中显示 {00.00} 这种格式?
- firebase - Firebase 云函数传播运算符失败 eslint 检查和上传失败
- java - Java 通用 GetComponent 方法
- wordpress - Wordpress 菜单链接到 iframe
- wordpress - 如何使用查询更新 WordPress 数据
- javascript - 如何避免专注于 slickGoTo 事件
- sql - 如何将许多(和不同的)单元格从一行合并到具有较少单元格的多行?
- unit-testing - 使用 mocha webpack 为 Vue.js 前端编写单元测试用例时找不到模块问题