更新 table 仅当子查询 returns 结果 postgres

update table only if subquery returns the result postgres

我有查询可能不会 return 结果会导致 NULL 值

update public.test set geom = 
    (select geom from public.test where st_geometrytype(geom) = 'X' limit 1)

我尝试添加 COALESCE 以替换为原始值但出现错误

update public.ec_1_eur_1 set geom = 
        COALESCE(select geom from public.ec_1_eur_1 where 
st_geometrytype(geom) = 'X' limit 1, geom)

另外这也会报错

with s2 as (select geom from public.test where st_geometrytype(geom) = 'X' limit 1)
update public.test set geom = s2 where s2 is not null

我会在这里使用 update/join 语法,所以如果子查询 returns 没有行,则不会更新任何内容:

update public.test t
set geom = t1.geom
from (
    select geom 
    from public.test 
    where st_geometrytype(geom) = 'X' 
    limit 1
) t1

至于您要使用 coalesce() 编写的查询:您需要用括号将子查询括起来,因此它 returns 是一个标量是明确的:

update public.test t
set geom = coalesce(
    (select geom from public.test where st_geometrytype(geom) = 'X' limit 1),
    geom
)

但是这种方法效率较低,因为如果子查询returns 没有行,它仍然会将table 的所有行更新回它们的原始值;在这方面,update/join 方法更可取。

但是请注意,没有 order bylimit 没有什么意义,因为它不是确定性的;当子查询产生多行时,未定义将选择哪一行。