postgresql Postgres 11更新冲突查询

wa7juj8i  于 2023-10-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(167)

假设我有一个带约束的表的更新查询(Postgres 11)。
我不知道这些约束,因此无法确定更新查询是否会失败。
如果更新查询由于冲突而失败,我不想做任何事情并返回0(没有更新任何行)。
有了一个插入,你可以有'插入. ON CONFLICT DO NOTHING“,但此选项在更新查询中不存在。
有解决办法吗?

f2uvfpb9

f2uvfpb91#

您可以尝试使用CTE获取UPDATE语句的结果,然后使用RETURNING *返回更新的行,但如果由于冲突而失败,则不会返回任何内容。

  1. WITH updated_rows AS (
  2. UPDATE your_table
  3. SET column1 = 'new_value'
  4. WHERE condition
  5. RETURNING *
  6. )
  7. SELECT COUNT(*) AS rows_updated FROM updated_rows;
cl25kdpy

cl25kdpy2#

这不是一个直接的答案,但没有理由做出这样的声明:* 我不知道...所以我不能...* 相反,这应该引发一个问题:* 我该怎么...* 在这种情况下,这将是,我如何确定一个表上的约束?* 以下是其中一种方法:

  1. select table_name, constraint_name, constrant_definition
  2. from (select distinct on(con.conrelid::regclass::text,con.conname,con.contype)
  3. con.conrelid::regclass::text table_name
  4. , con.conname constraint_name
  5. , con.contype
  6. , pg_get_constraintdef(con.oid) constrant_definition
  7. from pg_catalog.pg_constraint con
  8. join pg_catalog.pg_class rel on rel.oid = con.conrelid
  9. join pg_catalog.pg_namespace nsp on nsp.oid = con.connamespace
  10. where nsp.nspname = 'public'
  11. and rel.relname = 'non_standard_calendar'
  12. ) sq
  13. order by table_name
  14. , case when contype = 'p' then 1
  15. when contype = 'u' then 2
  16. when contype = 'f' then 3
  17. when contype = 'c' then 4
  18. else 5
  19. end;

然后,有了这些信息,你可以提出一个更好的问题,你的问题,或使问题静音。

展开查看全部

相关问题