I must query some objects that are close to a city. They must be sorted according to the user's location.
So I decided to write a SQL query which uses two times the Pythagoras formula.
It seems to get the good objects (close to the city), but it fails in sorting them correctly according to the user's location.
Do you know if I correctly use SQL or if it's the formula which goes wrong?
Data
In the following query...
distance
stores the distance between the objects and the city.distance_2
stores the distance between the objects and the user's location.lat
andlon
are the coordinates of the objects. The query is indeed executed in the table of the objects.
User's location
- 47.643310
- -2.805655
City's location
48.51666700
-2.78333300
Found objects' location
Closest-to-the-user object
47,6593484
-2,7546085
Farest-to-the-user object
48,4962385
-2,7642788
Query
SELECT *,
SQRT((48.51666700 - lat) * (48.51666700 - lat) + ((-2.78333300 - lon) * COS(RADIANS(lat))) * ((-2.78333300 - lon) * COS(RADIANS(lat)))) * 111.325 AS distance,
SQRT((47.64331000 - lat) * (47.64331000 - lat) + ((-2.80565500 - lon) * COS(RADIANS(lat))) * ((-2.80565500 - lon) * COS(RADIANS(lat)))) * 111.325 AS distance_2
FROM restaurants WHERE 1=1 AND visible = 1 HAVING distance < 200 ORDER BY distance_2 ASC
Order of showing
The farest object is displayed before the closest, which isn't normal (see next part).