【问题标题】:update table only if subquery returns the result postgres仅当子查询返回结果 postgres 时才更新表
【发布时间】:2021-03-15 22:43:00
【问题描述】:

我的查询可能不会返回导致 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

【问题讨论】:

    标签: sql postgresql sql-update subquery inner-join


    【解决方案1】:

    我会在这里使用更新/连接语法,因此如果子查询没有返回任何行,则不会更新任何内容:

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

    至于你想写的查询,使用coalesce():你需要用括号括住子查询,所以它返回一个标量是明确的:

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

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

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

    【讨论】:

    • 实际查询是按顺序根据相交的几何形状检查区域,但我不想为这个问题写那个复杂的查询
    猜你喜欢
    • 1970-01-01
    • 2020-04-06
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多