I have a table like the following:-
Table: deals +----+-------+----------+----------+------------+ | ID | name | latitude | longitude| end_date | |----+-------+----------+----------+------------+ | 1 | pizza | 10.5 | -10.5 | 2012-12-12 | | 2 | pizza | 11.5 | -10.5 | 2012-12-12 | | 3 | jelly | 21.5 | -10.5 | 2012-12-12 | | 4 | jelly | 23.5 | -10.5 | 2012-12-12 | | 5 | lily | 19.5 | -10.5 | 2012-12-12 | +----+-------+----------+----------+------------+
I’m using the latitude and longitude to find the distance to that person. But I need result to be DISTINCT based on name. I also need to sort the results by the distance I calculated and apply the limit 0,3.
The query I’m currently using is”-
SELECT *,
( 6371 * Acos(Cos(Radians(9.939625)) * Cos(Radians(lat)) * Cos(
Radians(lng) - Radians(76.259498)) +
Sin(Radians(9.939625)) * Sin(Radians(lat))) ) AS
distance
FROM deals
WHERE 1
AND end_date >= Now()
HAVING distance < 20000
ORDER BY id DESC,
distance
LIMIT 0, 3;
So in short, what I need is:-
- List of the closest deals (sorted by distance)
- Apply distinct to
name(so that both pizza and jelly will appear only once)
You’ll want to apply
MINto get the minimum distance per name,GROUP BYname (which gives one result per name) andORDER BYdistance first and id later;I should add that this query may be ok for your case but isn’t generally very useful, since if you want to know for example the latitude and longitude of the closest pizza place, you’ll need an entirely different query.