我有一个包含位置的mysql表,例如:
ID latitude longitude value
1 11.11111 22.22222 1
2 33.33333 44.44444 2
3 11.11112 22.22223 5
我想选择彼此靠近的记录(在上面的例子中,第1行和第3行),这样我就可以将它们作为一条记录插入新表中。通过说近,让我们说100米。我想新表是:
ID latitude longitude value
1 11.11111 22.22222 3
2 33.33333 44.44444 2
如您所见,我想保留第一条记录的坐标,并在列'值'中插入两条记录的平均值。
我用于距离的公式如下:
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.
该公式适用于短距离。
所以,我的问题不是转换lat,lon到distance而是我的SQL。我知道如何选择距离特定纬度,离子坐标最远距离为100米的记录,但我不知道如何选择彼此距离最大的记录。
我做的一种方式 - 它的工作原理 - 通过在PHP中逐个循环记录并为每个记录,进行SQL查询以选择接近的记录。但是这样,我在循环中进行SQL查询,据我所知,这是一种不好的做法,特别是如果记录数以千计。
我希望我很清楚。如果没有,我很乐意为您提供更多信息。
感谢您的帮助。
答案 0 :(得分:1)
这是一个获取范围内所有位置的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是里程的常数。