为表中的每一行选择最近的点

6rvt4ljy  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(412)

我用这个来找到最近的点

SELECT 
  id, 
  ST_Distance(
   POINT(52.760667210533,-7.22646337599035),
   geo_point
  ) as distance 
from Points 
order by distance limit 1

我有一个包含所有候选点的temppoints临时表,我想将它们标准化到osm节点上,但是有很多,所以我需要一个查询来在一个调用中解析它们。union不允许我使用order-by,我的db-raw查询接口也不允许我触发一系列以“;”分隔的查询。临时表有lat和lon,但也可以很容易地有一个点。我怎么走

select id,NearestTo(TempPoint.geo_point,Points) from TempPoints;

编辑:我可以在我的大型联合查询中插入每个select,这解决了我的问题。
我仍然希望能加入最近的一排。

r6hnlfcb

r6hnlfcb1#

我的解决方案是发出一系列查询,每行一个,并用联合将它们绑定在一起。mysql堆栈最终会崩溃,所以您需要分块执行,但默认安装1000就可以了。您必须将查询括起来,因为它们包含order by。有些点可能会失败,所以我给它们都贴上了文字行的标签,这样你就可以编辑和过滤原稿了。您还需要使用

WHERE Contains(<polygon>,point)

子句,否则它将尝试对整个表进行排序,其中polygon是一个边界框,您必须使用geomfromtext()和polygon()进行处理。当然,在列上还需要一个特殊的空间索引!。这里有一些代码

var SMALL=0.001

            var=query=points
                .map(function(point){
                    var bottom=point.lat+SMALL
                    var top=point.lat-SMALL
                    var left=point.lon-SMALL
                    var right=point.lon+SMALL
                    var polygon=[
                        [bottom,left],
                        [top,left],
                        [top,right],
                        [bottom,right],
                        [bottom,left]
                    ]
                    polygon="POLYGON(("+polygon.map(function(point){
                        return point.join(' ')
                    })
                    .join(",")+"))"

                    point.line_no=line_no++
                    return "(SELECT "+point.line_no+" as line_no,id, ST_Distance(POINT("+
                                point.lat+","+point.lon+
                                "),geo_point) as distance"+
                                " from Points "+
                                " WHERE Contains(GeomFromText('"+polygon+"'),geo_point) "+
                                " order by distance limit 1) "
                })
                .join(" UNION ")+" order by line_no"
            return sequelize.query(query)
zzzyeukh

zzzyeukh2#

这可能适合您:

SELECT t.id as tid, p.id as pid, p.geo_point
FROM TempPoint t
JOIN Points p ON p.id = (
    SELECT p1.id
    FROM Points p1
    ORDER BY ST_Distance(p1.geo_point, t.geo_point)
    LIMIT 1
)

相关问题