Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 基于两列从另一个Postgres插入到一个表中_Sql_Postgresql_Sql Insert - Fatal编程技术网

Sql 基于两列从另一个Postgres插入到一个表中

Sql 基于两列从另一个Postgres插入到一个表中,sql,postgresql,sql-insert,Sql,Postgresql,Sql Insert,我有两个具有相同列的表,这些表没有唯一的列。假设列为Col1、Col2、Col3和Col4。表是T1和T2 我要做的是插入从T2到T1的所有行,其中Col1和Col2组合在T1中不存在。Col1是字符串,Col2是int 例如,Col1=“苹果”和Col2=“2019”。如果一行在T2中包含Col1=“APPLE”和Col2=2019,我不想将其插入T1,而如果一行包含Col1=“APPLE”和Col2=2020,我想将其插入T1 我正试图找到最简单的解决方案,但似乎找不到一种直接的方法,即在不

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

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

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


我正试图找到最简单的解决方案,但似乎找不到一种直接的方法,即在不存在的地方使用INSERT INTO或使用UPSERT

带有
的不存在

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
)

请参阅简化版。

您可以使用
插入。。。选择。。。不存在的地方
要比较的元组相等(
col1,col2)


您对
t1(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)
)