【问题标题】:How to use on conflict on constraint in postgres with update query如何在带有更新查询的postgres中使用约束冲突
【发布时间】:2022-10-14 02:57:40
【问题描述】:

我想更新我的数据库中的“名称”列,它有超过 300000 条记录。 name 字段有一个唯一的约束

批量更新时,我想跳过违反约束的记录

update "profiles" set name = left(name, -1) 
where ---------
ON CONFLICT ON CONSTRAINT profiles_name_key 
DO NOTHING

上面的查询在“ON”上抛出错误

编辑

不必使用 ON CONFLICT。任何可以更新不与约束冲突的记录的查询都可以工作

【问题讨论】:

  • 没有UPDATE ... ON CONFLICT。如果你想做一个“upsert”,你需要INSERT ... ON CONFLICT。在此处查看UPDATE 语法:postgresql.org/docs/current/sql-update.html
  • 或者您可能需要 MERGE,这是 PostgreSQL v15 中的新功能。
  • 我不需要更新。如果没有冲突,我只想更新。还有其他方法可以实现吗?

标签: sql postgresql


【解决方案1】:

你不能用 update ... on conflict 得到你想要的东西——那个结构不存在.但是您可以通过交易块获得它。虽然你会得到一个例外,但你可以拦截它并继续处理。 (见demo

do $$
begin 
    begin -- nested block 
        update <table> 
           set <column> = '<existing value'
         where <column> = '<other existing value>';
    exception 
        when others then null;
    end;  -- nested block
    
    -- other code here will still execute

end ; 
$$;

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 2013-02-16
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2016-05-04
    • 2022-12-05
    相关资源
    最近更新 更多