0

我有两个具有相同列的表,这些表没有唯一的列。假设这些列是 Col1、Col2、Col3 和 Col4。表格是 T1 和 T2。

我想要做的是插入从 T2 到 T1 的所有行,其中 Col1 和 Col2 组合在 T1 中已经不存在。Col1 是一个字符串,而 Col2 是一个 int。

例如 Col1 = "APPLE" 和 Col2 = "2019"。如果一行在 T2 中包含 Col1 = "APPLE" 和 Col2=2019,我不想将其插入到 T1 中,而如果一行包含 Col1 = "APPLE" 和 Col2=2020,那么我想将其插入到 T1 中。

我正在尝试找到最简单的解决方案来执行此操作,但似乎无法找到使用 INSERT INTO WHERE NOT EXISTS 或使用 UPSERT 的直接方法。

4

2 回答 2

0

NOT EXISTS

insert into t1(Col1, Col2, Col3, Col4)
select Col1, Col2, Col3, Col4
from t2
where not exists (
  select 1 from t1
  where t1.Col1  = t2.Col1 and t1.Col2  = t2.Col2
)

查看简化的演示

于 2019-12-12T23:16:50.013 回答
0

您可以使用insert ... select ... where not existswith tuple 相等性来比较 ( col1, col2):

insert into t1(col1, col2, col3, col4)
select * from t2
where not exists (
    select 1 from t1 where (t1.col1, t1.col2) = (t2.col1, t2.col2)
)
于 2019-12-12T23:18:07.110 回答