Pergunta

I want to select the closest place to a given longitude, latitude values so I have created this query

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

The main idea is that this formula returns the distances between all points and my hardcoded one I have tried the formula in select query and it's working.

I want to get "the minimal" distance and I need something like "IS MINIMAL". I know the above is wrong (maybe very wrong and stupid) but I'm new in these areas. I think I only have to add or change a word or two and it will work, but I don't know the correct ones.

Foi útil?

Solução

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?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top