【发布时间】:2018-01-25 19:32:07
【问题描述】:
在 Postgres 10 中,我想执行两次 UPDATE。无论如何,第一个 UPDATE 都应该运行,更新alwaysupdate 列。只有当下面的 SELECT 语句返回的行数为 0 时,第二个 UPDATE 才应该运行,这意味着只有当 mytable 中的所有行都将 sometimesupdate 设置为 null 时,sometimesupdate 才应该更新。 .
-- Run no matter what, updating 'alwaysupdate'
update mytable set alwaysupdate = now() where keyA = 100 and keyB = 200
-- Check the number of rows where 'sometimesupdate' has a value
select count(*) from mytable where keyB = 200 and sometimesupdate is not null
-- If 'sometimesupdate' is null for all rows above, give it a value in this row
update mytable set sometimesupdate = now() where keyA = 100 and keyB = 200
最有效的方法是什么?是否可以将其组合成单个 SQL 语句?否则包含在事务中的多个语句?否则,必要时使用函数。
【问题讨论】:
标签: sql postgresql sql-update