根据两列从另一个Postgres插入一个表

时间:2019-12-12 23:12:21

标签: sql postgresql sql-insert

我有两个具有相同列的表,这些表没有唯一的列。可以说列是Col1,Col2,Col3和Col4。这些表是T1和T2。

我想做的是插入从T2到T1的所有行,其中Tol中已经没有Col1和Col2组合。 Col1是字符串,而Col2是int。

因此例如Col1 =“ APPLE”和Col2 =“ 2019”。如果一行在T2中包含Col1 =“ APPLE”且Col2 = 2019我不想将其插入T1,而如果一行包含Col1 =“ APPLE”且Col2 = 2020则我想将其插入T1。

我正在尝试找到最简单的解决方案,似乎无法使用INSERT INTO WHERE NOT EXISTS或UPSERT找到简单的方法。

2 个答案:

答案 0 :(得分: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
)

查看简化的demo

答案 1 :(得分:0)

您可以将insert ... select ... where not exists与元组等式进行比较(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)
)