没有重复项时,为什么我的PostgreSQL插入语句中存在重复的主键错误?

问题描述

注意:阅读一些评论后,我将查询更新为以下内容,该方法可以正常工作。但是也许有一个更简洁的解决方案。 这似乎可以解决问题……

insert into duplicates(contact_id_a,contact_id_b,ignore_duplicate,has_been_fetched,list_id,contact_a_name,contact_b_name) 
SELECT 32753,42260,false,567,(select data->>'firstname' as ca_firstname from contacts where contact_id = 32753),(select data->>'firstname' as cb_firstname from contacts where contact_id = 42260) 
WHERE NOT EXISTS ( SELECT * FROM duplicates WHERE list_id = 567  
                  AND ((contact_id_a = 32753 and contact_id_b = 42260) OR (contact_id_a = 42260 and contact_id_b = 32753) ));

为什么我的postgreSQL查询在没有重复项时会引发此重复的主键错误

ERROR:  duplicate key value violates unique constraint "duplicates_pkey"
DETAIL:  Key (contact_id_a,list_id)=(32753,567) already exists.
sql state: 23505

重复项表为空,因此我可以想象新行是唯一的。

这是查询。简而言之,我正在做什么,但总而言之,仅当重复表中没有包含指定的contact_id的行时,才将新行插入包含第二个名为contacts的表中的名称信息的重复表中和list_id。

insert into duplicates(contact_id_a,ca.data->>'firstname',cb.data->>'firstname'
from contacts c 
left join contacts ca on ca.list_id=567 and ca.contact_id = 32753 
left join contacts cb on cb.list_id=567 and cb.contact_id = 42260 
WHERE NOT EXISTS ( SELECT * FROM duplicates WHERE list_id = 567  
                  AND ((contact_id_a = 32753 and contact_id_b = 42260) OR (contact_id_a = 42260 and contact_id_b = 32753) ));

这是我的主键约束...

enter image description here

解决方法

在执行任何操作之前,请尝试转储数据库,以便在出现任何问题时可以返回到当前状态,然后尝试重新索引数据库:

REINDEX DATABASE <YOUR-DBNAME>;

抽真空可能也是个好主意: vacuum(full,analyse,verbose);

,

select使用相同的键组合返回多个行。

您需要修正选择查询,以便每个键组合仅返回一行。

也许可以使用distinct摆脱困境:

insert into duplicates (...) 
select distinct ...