开发者

postgresql: error duplicate key value violates unique constraint

This question have been asked by several people but my problem seems to be different.

Actually I have 开发者_开发问答to merge same structured tables from different databases in postgresql into a new DB. What I am doing is that I connect to remote db using dblink, reads that table in that db and insert it into the table in the current DB like below

INSERT INTO t_types_of_dementia SELECT * FROM dblink('host=localhost port=5432 dbname=snap-cadence password=xxxxxx', 'SELECT dementia_type, snapid FROM t_types_of_dementia') as x(dementia_type VARCHAR(256),snapid integer);

First time this query runs fine, but when I run it again or try to run it with some other remote database's table: it gives me this error

ERROR: duplicate key value violates unique constraint "t_types_of_dementia_pkey"

I want that this new tables gets populated by entries of others tables from other dbs. Some of the solutions proposed talks about sequence, but i am not using any

The structure of the table in current db is

CREATE TABLE t_types_of_dementia(
    dementia_type VARCHAR(256),
    snapid integer NOT NULL,
    PRIMARY KEY (dementia_type,snapid)
);

P.S. There is a specific reason why both the columns are used as a primary key which may not be relevant in this discussion, because same issue happens in other tables where this is not the case.


As the error message tells you - you can not have two rows with the same value in the columns dementia_type, snapid since they need to be unique.

You have to make sure that the two databases has the same values for dementia_type, snapid.

A workaround would be to add a column to your table alter table t_types_of_dementia add column id serial generated always and use that as primary key instead of your current.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜