mysql - select 彼此距离较近的记录

mysql - select records with near distance from each other

我有一个 mysql table 包含位置,例如:

ID  latitude  longitude  value
1   11.11111  22.22222   1
2   33.33333  44.44444   2
3   11.11112  22.22223   5

我想要 select 彼此靠近的记录(在上面的示例中,第 1 行和第 3 行),以便我可以将它们作为一条记录插入到新的 table 中.说近,比方说 100 米。我希望新的 table 是:

ID  latitude  longitude  value   
1   11.11111  22.22222   3
2   33.33333  44.44444   2

如您所见,我想保留第一条记录的坐标,并在 'value' 列中插入两条记录的平均值。

我使用的距离公式如下:

R*SQRT(((lon2*c-lon1*c)*cos(0.5*(lat2*c+lat1*c)))^2 + (lat2*c-lat1*c)^2)

哪里

[lat1, lon1] the coordinates of the first location,
[lat2, lon2] the coordinates of the second location,
[R] the average radius of Earth in meters,
[c] a number to convert degrees to radians.

该公式适用于短距离。

所以,我的问题不是纬度、经度到距离的转换,而是我的 SQL。我知道如何 select 记录与特定纬度、经度坐标的最大距离为 100 米,但我不知道如何 select 记录彼此之间的最大距离。

我做到这一点的一种方法 - 并且它有效 - 是通过在 PHP 中一个一个地循环记录并且对于每个记录,对 select 记录进行 SQL 查询在附近。但是通过这种方式,我在循环中执行了一个 SQL 查询,据我所知,这是一种不好的做法,尤其是当记录将达到数千条时。

我希望我说的很清楚。如果没有,我很乐意为您提供更多信息。

感谢您的帮助。

这里是SQL获取范围内的所有地方:

SELECT 
    ID,
    latitude,
    longitude,
    (6371 * acos (cos( radians(origin.latitude)) * cos( radians( destination.latitude )) 
        * cos( radians(destination.longitude) - radians(origin.longitude)) + sin(radians(origin.latitude)) 
        * sin( radians(destination.latitude)))) AS distance
FROM myTable as destination, myTable as origin
WHERE destination.id = myId
HAVING distance < 100 --some value in kilometers

6371 是公里的常数。 3959 是英里的常数。

此主题有更多答案:MySQL Great Circle Distance (Haversine formula)