如何使用连接更新空值?

问题描述

我使用 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 更新方式的 node_id。但是,如果任何节点被删除修改到另一个位置,则在再次运行查询后,end_node_id 应设置为 null。

如何更改此 sql

解决方法

可能最简单的方法是在更新之前将所有内容都设置为 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;