【问题标题】:Get nearest neighbor point from a table closest to the point in a given row of another table从最接近另一个表的给定行中的点的表中获取最近的邻居点
【发布时间】:2019-07-28 14:12:15
【问题描述】:

我有两张桌子,table_a 有多边形和这些多边形的质心。 table_b 有另一组点与table_a 中的几何重叠。

对于table_a 的每一行,我需要从table_b 中找到最靠近该行质心的点。

INSERT INTO nearest_node (nearest_drive_node) 
    SELECT osmid FROM london_drive_nodes 
    ORDER BY london_drive_nodes.geom <-> nearest_node.lsoa_centroid 
    LIMIT 1;

这会返回

SQL Error [42P01]: ERROR: invalid reference to FROM-clause entry for table "nearest_node"
  Hint: There is an entry for table "nearest_node", but it cannot be referenced from 
this part of the query.

我不确定如何使用来自table_a 的值作为查询的ORDER BY 部分中的点。我发现的示例是查找单个点的最近邻居作为文本字符串,而不是一列点。

【问题讨论】:

  • 您确定您不是在寻找更新子句 - 您根据最接近该行的 london_drive_nodes 设置 nearest_drive_node 吗?
  • 是的,你完全正确。 UPDATE 不是 INSERT 谢谢!

标签: postgresql postgis nearest-neighbor


【解决方案1】:

插入最近的节点作为表中的新行,没有任何其他属性,似乎是错误的。您肯定想要更新现有记录。

您必须为输入表的每一行计算最近的节点,这可以通过子查询来实现。

UPDATE nearest_node
SET nearest_drive_node = (
  SELECT london_drive_nodes.osmid
  FROM london_drive_nodes
  ORDER BY nearest_node.geom <-> london_drive_nodes.geom
  LIMIT 1
);

如果您只是选择(并最终将此信息插入到另一个表中),您将依赖横向连接:

select a.osmid,closest_pt.osmid, closest_pt.dist
from tablea a
CROSS JOIN LATERAL
  (SELECT
     osmid , 
     a.geom <-> b.geom as dist
     FROM tableb b
     ORDER BY a.geom <-> b.geom
   LIMIT 1) AS closest_pt;

【讨论】:

    【解决方案2】:

    问题似乎是您在查询中引用了nearest_node,而不是在FROM 子句中,但总的来说,您的查询无论如何“对于每一行”都不起作用。尝试将 st_distance 和常规 mingroup by 结合起来以获得最小距离,然后将其包装在 CTE 或子查询中以确定它实际上是哪个节点:

    WITH distances AS (
        SELECT nn.id, nn.lsoa_centroid, min(st_distance(ldn.geom, nn.lsoa_centroid)) as min_distance
        FROM london_drive_nodes ldn, nearest_node nn
        GROUP BY nn.id
    )
    INSERT INTO nearest_node (nearest_drive_node)
    SELECT ldn.osmid
    FROM distances
    JOIN london_drive_nodes ldn ON distances.min_distance = st_distance(distances.wgs84_centroid, ldn.wgs84_coordinates)
    

    【讨论】:

    • 请注意,st_distance 确实没有受益于空间索引,而 &lt;-&gt; 可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多