查询以获得最近的距离记录

时间:2016-09-09 11:27:27

标签: mysql gis

我有以下mysql查询:

SELECT a.id
     , ( 3959 * acos( cos( radians(a.latitude) ) * cos( radians( w.latitude ) ) 
              * cos( radians( w.longitude ) - radians(-a.longitude) ) 
              + sin( radians(a.latitude) ) * sin(radians(w.latitude)) ) ) distance 
  FROM global_restaurants a 
  JOIN webgeocities w 
    ON w.name = a.locality 
   AND w.country_code = a.country 
   AND a.latitude LIKE w.latitude
  JOIN states s 
    ON s.state_code = w.state_code 
   AND w.country_code = s.country_code
 WHERE a.city_id = 0 

执行后返回:

id distance
70 6665.478678743614
70 6496.46971480875
70 6725.900646648246
70 6733.5156930808
90 6969.449661399672
90 7252.889875588891

我希望它只返回最小距离的2行,如:

id distance
70 6496.46971480875
90 6969.449661399672

2 个答案:

答案 0 :(得分:0)

在查询末尾添加order by

order by distance ASC LIMIT 2;

现在你计算距离但是 在查询结束时,您必须对它们进行排序并限制返回行计数..

注意:

我认为你的查询有一个小错误 3959是里程,但我认为这些值是以米为单位

您的完整查询可以是这样的:

select a.id, ( 6371000 * acos( cos( radians(a.latitude) ) * cos( radians( w.latitude ) ) 
* cos( radians( w.longitude ) - radians(-a.longitude) ) + sin( radians(a.latitude) ) * sin(radians(w.latitude)) ) ) AS distance 
from `global_restaurants` as a INNER JOIN webgeocities as w ON (w.name = a.locality AND w.country_code = a.country and a.latitude like w.latitude) INNER JOIN 
states AS s ON (s.state_code = w.state_code and w.country_code = s.country_code) where a.city_id = '0' ORDER BY distance ASC LIMIT 2;

答案 1 :(得分:-1)

为简单起见,我们假设您在查看中有查询 - 堆栈,那么您的查询应该如下所示

select stack.* from stack join (
SELECT id, GROUP_CONCAT(distance ORDER BY 
distance asc) grouped_distance FROM stack GROUP BY id
) group_distance on group_distance.id=stack.id
where find_in_set(stack.distance,group_distance.grouped_distance)between 1 and 2;