First time posting, I will try to adhere to best practices.
I’m trying to construct a MySQL query that measures a user’s location (represented in the query as $Lat and $Lng for latitude and longtitude, respectively). The query should return the 50 stations in closest proximity to the user.
The problem is that the data in my table contains the location of each station entrance per station and I only need the closest station entrance per station!
This is my query:
SELECT id, lat, lng, station_name, routes,
( 3959 * acos( cos( radians($Lat) )
* cos( radians( lat ) ) * cos( radians( lng ) -
radians($Lng) ) + sin( radians($Lat) ) * sin( radians( lat ) ) ) ) AS distance
FROM subway_stations ORDER BY distance LIMIT 0 , 50;
The Above MySQL query accomplishes the following:
- Selects the data from id, lat, lng, station_name and routes
- Measures lat and lng of each station with that of the user – storing that data as ‘distance’
- Returns the 50 nearest results
I need to group these results together so that only one record per station is returned, the one with the lowest value in the distance column, which is the station entrance closest to the user.
I’ve tried using GROUP BY but I seem to be implementing it incorrectly as the results returned were not the desired ones.
It’s hard to know without setting up a sample database, but I suspect that you want to make the following changes:
Add a
group by station_name, id, lat, lngto the end of your queryAll
selectfields which are not a part of thegroup byclause need an aggregating function. Most obviously,distanceshould needs amin(...)I’m not sure if the
orderandlimitclause can be used. If you have problems, take them out (temporarily) and get this much working. For my convenience, call this query Q1.If the
order byandlimitclause cannot be used (experiment and see), then you want a nested query. That will look something likeselect * from (...Q1...) t1 ORDER BY distance LIMIT 0,50. Thet1assigned a temporary name to the inner select, not actually used in this query, but required for syntax.As an optimization, you may want to add a
havingclause to the innerQ1query. That is, addHAVING distance<XXXXX, if you know a bounding distance.Note that steps 3 — 5 may not be needed, I’m not sure about step 3.