【问题标题】:How do you make a update idempotent in a primary key in postgresql?如何在 postgresql 的主键中使更新幂等?
【发布时间】:2021-03-08 05:14:33
【问题描述】:

我有这个错误:

SQL 错误 [23505]:错误:重复键值违反唯一约束“name_pkey” 详情:Key (status_id, type)=(0, 1) 已经存在。

当我执行这个更新脚本时:

update schema.table_name
    set type = '1'
    where status_id in ('AT', '0', '1',);

【问题讨论】:

  • 表中已经有一行状态为0,类型为1,并且你有一个禁止重复的唯一键。你想怎么处理?

标签: sql postgresql


【解决方案1】:

主键在(status_id, type) 上,这意味着您已经拥有以下多对的行:

AT    1
0     1
1     1

所以,更新不起作用。您可以通过过滤掉潜在冲突来忽略密钥:

update schema.table_name t
    set type = '1'
    from (values ('AT'), ('0'), ('1')) v(status_id)
    where t.status_id = v.status_id and
          not exists (select 1
                      from schema.table_name t2
                      where t2.status_id = t.status_id and t2.type = '1'
                     );

这只是忽略了可能发生的更新。

【讨论】:

  • UPDATE 不支持on conflict
  • @a_horse_with_no_name 。 . .谢谢谢谢。我知道——而且没有数据库支持它。但它真的很有用!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 2010-10-18
  • 2022-12-12
  • 1970-01-01
  • 2019-04-02
  • 2022-11-21
相关资源
最近更新 更多