我正在寻找一个快速的MySQL查询,可以从一个简单的表中返回最近的位置:
表格:locations:
客户端坐标(纬度 + 经度):
大多数提供的示例 @SO 都基于距离计算。
即使使用来自 Birmingham 的坐标,它仍然返回
表格:locations:
id | city | latitude | longitude
-----------------------------------------------
1 | Berlin | 52.524268 | 13.406290
-----------------------------------------------
2 | London | 51.508129 | -0.1280050
-----------------------------------------------
3 | Hamburg | 53.551084 | 9.9936817
-----------------------------------------------
客户端坐标(纬度 + 经度):
$intLat = '52.370215700000000000'; // lat Amsterdam
$intLon = '4.895167899999933000'; // lon Amsterdam
大多数提供的示例 @SO 都基于距离计算。
即使使用来自 Birmingham 的坐标,它仍然返回
id=1
(柏林)。查询应该返回伦敦,因为它比柏林更近。不应该吗?SELECT *, ( 3959 * acos( cos( radians($intLat) )
* cos( radians( latitude ) )
* cos( radians( longitude )
- radians($intLon) ) + sin(radians($intLat) )
* sin( radians( latitude ) ) ) ) AS distance
FROM locations
HAVING distance < 10
AND id IN(1,2,3)
LIMIT 1;
distance
没有在其他地方使用且不需要distance < 10
,那么可以省略*3959
和acos()
步骤。另外,反转、排序,然后再处理。 - chux - Reinstate Monica