0

我想选择最接近给定经度、纬度值的地方,所以我创建了这个查询

SELECT *
FROM   "Places"
WHERE  2 * atan2(
sqrt(
sin((radians(41.647780 - latitude))/2)*sin((radians(41.647780 - latitude))/2) + 
sin((radians(25.295330 - longitude))/2)*sin((radians(25.295330 - longitude))/2) * 
cos(radians(latitude)) * cos(radians(41.647780))
),
sqrt(1 - 
sin((radians(41.647780 - latitude))/2)*sin((radians(41.647780 - latitude))/2) + 
sin((radians(25.295330 - longitude))/2)*sin((radians(25.295330 - longitude))/2) * 
cos(radians(latitude)) * cos(radians(41.647780))
)) * 6371 IS MINIMAL
LIMIT 1

主要思想是这个公式返回所有点之间的距离和我在选择查询中尝试过的硬编码的点之间的距离并且它正在工作。

我想获得“最小”的距离,我需要像“IS MINIMAL”这样的东西。我知道以上是错误的(可能非常错误和愚蠢),但我在这些领域是新手。我想我只需要添加或更改一两个单词就可以了,但我不知道正确的单词。

4

1 回答 1

1

What you are looking for is ORDER BY .. LIMIT 1:

SELECT *
FROM   "Places"
ORDER  BY atan2(
   sqrt(
   sin((radians(41.647780 - latitude))/2)*sin((radians(41.647780 - latitude))/2) + 
   sin((radians(25.295330 - longitude))/2)*sin((radians(25.295330 - longitude))/2) * 
   cos(radians(latitude)) * cos(radians(41.647780))
   ),
   sqrt(1 - 
   sin((radians(41.647780 - latitude))/2)*sin((radians(41.647780 - latitude))/2) + 
   sin((radians(25.295330 - longitude))/2)*sin((radians(25.295330 - longitude))/2) * 
   cos(radians(latitude)) * cos(radians(41.647780))
   ))
LIMIT  1;

You might be interested in PostGis or this related question:
How can I get results from a JPA entity ordered by distance?

于 2013-11-14T22:01:49.013 回答