You need to enable JavaScript to run this app. PostgreSQL使用INSERT ON CONFLICT实现插入更新时冲突报错如何处理
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL使用INSERT ON CONFLICT实现插入更新时冲突报错如何处理

错误原因
  • 你当前执行的INSERT语句中,SELECT生成的待插入数据里存在多条(code, date, type)三个主键字段值完全相同的重复行
  • PostgreSQL的ON CONFLICT DO UPDATE逻辑要求,单次INSERT操作中不能有两条及以上的待插入行命中同一个冲突约束,也就是不能在同一次操作中多次更新同一行,因此触发了该报错。
解决方法

你需要先对SELECT生成的待插入数据按主键字段做分组聚合,提前统计每个主键组合的出现次数,再执行插入更新操作,修改后的SQL如下:

create table test
(
    code   varchar,
    date   date,
    code_2 varchar(2),
    type   varchar(4),
    sum    int default 1
);

alter table test
    add primary key (code, date, type);

insert into test(code, date, code_2, type, sum)
select 
    code,
    date,
    -- 同一个主键组合下code_2可按需求调整取值逻辑,此处取分组内任意一个即可
    max(code_2) as code_2,
    type,
    -- 统计当前批次里该主键组合的出现次数作为增量
    count(*) as batch_count
from (
    select 
        (array ['abc', 'xyz'])[ceil(random() * 2)] as code,
        (array ['2021-05-28', '2021-05-27'])[ceil(random() * 2)]::date as date,
        (array ['qq', 'ee'])[ceil(random() * 2)] as code_2,
        (array ['ABCD', 'DCBA'])[ceil(random() * 2)] as type
    from generate_series(1, 1000)
) t
group by code, date, type
on conflict (code, date, type)
do update set sum = test.sum + excluded.sum;
  • 上述写法先把随机生成的1000条数据按主键分组,避免了同批次待插入数据存在重复主键的问题
  • 冲突更新时直接把原有sum值加上本次批次的增量,即可实现你要求的计数累加需求。

内容的提问来源于stack exchange,提问作者bt ra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 06:06:04