【发布时间】:2020-07-03 22:14:01
【问题描述】:
我想查询表 A 中每个点 (id) 到表 B 中每个多边形 (id) 的距离。对于距离计算,我使用 ST_Distance。但是,ST_Distance(显然)返回到每个多边形的距离。但我只需要每个点的“最接近”结果。到目前为止,我尝试了以下查询,它返回了正确的结果,但(当然)只针对一个点。
SELECT polygons.id, points.id, ST_Distance(points.geom, polygons.geom)
FROM table_A AS points, table_B AS polygons
ORDER BY st_distance ASC LIMIT 1
结果应该是这样的:
polygon_id | point_id | min(distance)
-------------------------------------
1234 | 876 | 54.32
... | ... | ...
-------------------------------------
你有什么提示吗?非常感谢。
更新 1
WITH CTE AS
(SELECT polygons.id as poly_id, points.id as point_id,
ST_Distance(points.geom, polygons.geom) as thedistance ,
row_number() OVER
(PARTITION BY points.id ORDER BY ST_Distance(points.geom, polygons.geom))
FROM
table_A AS points
INNER JOIN table_B AS polygons
ON ST_DWithin(points.geom, polygons.geom, 100)) SELECT * FROM CTE WHERE row_number = 1
运行上述查询(3h 24m)后返回空结果。但是,应该有结果。会不会是括号有问题?
更新 2
SRID 为 4326 (WGS84),多边形为 OSM 构建多边形,点为同一城市中的任意点。
【问题讨论】:
标签: postgresql postgis