I am trying to come up with the most efficient way to resolve the following problem. I have a large table locations
in which points are stored using two doubles, one for Lat
and one for Lng
, which are indexed, as well as a radius
.
I am trying to select all locations
that are within the radius of a given Latitude and Longitude. My current approach is to run a subquery that first gathers all results within a "geographic square", and then from those results, calculate the distance and determine whether it is within range like so:
Subquery (select only those within a rough mile x mile square):
SELECT * FROM events WHERE $lat +0.015 > lat AND lat > $lat-0.015 AND $lng +0.02 > lng AND lng > $lng-0.02
Determine distance via Haversine:
SELECT * FROM ( the subquery ) WHERE Radius >= ( 20903520 * acos( cos(RADIANS(Lat)) * cos(RADIANS($lat)) * cos(RADIANS(Lng - $lng)) + sin(RADIANS(Lat)) * sin(RADIANS($lat))))
My question is, what is a better way of approaching this? I'm fairly sure this is among the least efficient ways of going about this and any help is greatly appreciated.