【问题标题】:How to update with join for null values?如何使用连接更新空值?
【发布时间】:2021-01-15 12:45:26
【问题描述】:

我将使用update from 更新我的空间数据,如下所示。

update ways w
    set end_node_id = n.node_id
from nodes n
where st_endpoint(w.shape) = n.shape 
   and w.created_at >= current_date 
   and w.created_at < current_date + interval '1 day';

此查询将end_node_id of way 更新为node_id of nodes 表。但是如果有任何节点被删除或修改到另一个位置,end_node_id 应该在查询再次运行后设置为 null。

我怎样才能改变这个sql?

【问题讨论】:

    标签: sql postgresql postgis spatial-query


    【解决方案1】:

    可能最简单的方法是在更新之前将所有内容设置为NULL

    update ways w
        set end_node_id = NULL;
    

    然后您的更新会将NULL 更改为其他内容。这确实会产生两次更新某些(很多?)行的开销。但这很简单。

    另一种方法需要ways 上的主键;让我叫它way_id

    update ways w
        set end_node_id = n.node_id
    from ways w2 left join
         nodes n
         on st_endpoint(w2.shape) = n.shape
    where w2.way_id = w.way_id;
    

    【讨论】:

    • @barteloma 限制 NULL-update ,使用 NOT EXISTS()
    • 我不需要第一个查询end_node_id = NULL,第二个工作。
    • 您仍然会触摸所有行。 (这就是你删除评论的本质)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    相关资源
    最近更新 更多