-1

在 Postgres 9.6 中是否可以使用该命令获得on duplicate keyUPSERT 功能?COPY我有一个要导入 Postgres 的 CSV 文件,但它可能包含一些重复的键违规,因此该COPY命令会给出错误并在遇到它们时终止。

该文件非常大,因此可能无法在应用程序代码中对其进行预处理(以处理可能导致重复键违规的行),因为所有键可能不适合内存。

将大量行导入可能包含重复键违规的 Postgres 的最佳方法是什么?

4

1 回答 1

2

样本:

t=# create table s90(i int primary key, t text);
CREATE TABLE
t=# insert into s90 select 1,'a';
INSERT 0 1
t=# copy s90 from stdin delimiter ',';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 1,'b'
>> 2,'c'
>> \.
ERROR:  duplicate key value violates unique constraint "s90_pkey"
DETAIL:  Key (i)=(1) already exists.
CONTEXT:  COPY s90, line 1

使用副本的解决方法:

t=# create table s91 as select * from s90 where false;;
SELECT 0
t=# copy s91 from stdin delimiter ',';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> 1,'b'
>> 2,'c'
>> \.
COPY 2
t=# with p as (select s91.* from s91 left outer join s90 on s90.i=s91.i where s90.i is null)
insert into s90 select * from p;
INSERT 0 1
t=# select * from s90;
 i |  t
---+-----
 1 | a
 2 | 'c'
(2 rows)
于 2017-05-01T20:04:42.523 回答