PostGIS 两个大点集之间的最小距离

Mat*_* SM 3 postgis

我在 PostGIS 中有两个点表,比如 A 和 B,我想知道,对于 A 中的每个点,到 B 中最近点的距离是多少。我能够用以下查询:

SELECT a.id, MIN(ST_Distance_Sphere(a.geom, b.geom))
FROM table_a a, table_b b
GROUP BY a.id;
Run Code Online (Sandbox Code Playgroud)

但是,我在每个表中有几百万个点,并且这个查询无限期地运行。有没有更有效的方法来解决这个问题。我愿意得到一个近似的距离而不是一个精确的距离。

编辑:如果点未投影,则对 JGH 提供的答案稍作修改,以米而不是度数返回距离。

SELECT 
    a.id, nn.id AS id_nn, 
    a.geom, nn.geom_closest, 
    ST_Distance_Sphere(a.geom, nn.geom_closest) AS min_dist
FROM 
    table_a AS a
    CROSS JOIN LATERAL
        (SELECT
            b.id, 
            b.geom AS geom_closest
        FROM table_b b
        ORDER BY a.geom <-> b.geom
        LIMIT 1) AS nn;
Run Code Online (Sandbox Code Playgroud)

JGH*_*JGH 6

您的查询很慢,因为它在不使用任何索引的情况下计算每个点之间的距离。<->如果在order by子句中使用,您可以重写它以使用使用索引的运算符。

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