I have a query that returns all records, ordered by distance from a fixed point, compared to a POINT field in my MySQL 5.7 database.
For a simple example, lets say it looks like this:
SELECT shops.*, st_distance(location, POINT(:lat, :lng)) as distanceRaw
FROM shops
ORDER BY distanceRaw
LIMIT 50
My actual query also has to do a few joins to get additional data for the results.
The issue is, that in order to sort the data by distance, it needs to calculate the distance over every single record in the database (currently around 100,000 records).
I can't cache the query, as it would only be specific to those original coordinates.
Is there anyway to limit the data that has to be calculated? E.g a reliable rough calculation for nearby shops, say +/- 3 degrees for the lat + lng? So that it only has to process a subset of the data?
If anyone has any experience in this sort of optimisation, I'd love some advice, thanks.