Okay, I need some help🙁 .
I have a website and maintain a member database of over 17,000 members. I have a table which contains for each member, among other things, their zipcode/postal code.
I also have a table with every zipcode/postal code, latitude, and longitude in North America.
I have successfully formed a query to select all members, and their distance, from the aforementioned tables. It is as follows:
// given [gathered beforehand]:
$lat = 39.9538; // latitude of center of radius
$lon = -74.995; // longitude of center of radius
$miles = 150; // radius distance
$query = "SELECT profiles.*,ROUND(1.15077 * 60.0 * degrees(acos(sin(radians($lat))*sin(radians(latitude))+cos(radians($lat))*cos(radians(latitude))*cos(radians(longitude) - radians($lon)))),0) as dist
FROM profiles,zipcodes
WHERE ((1.15077 * 60.0 * degrees(acos(sin(radians($lat))*sin(radians(zipcodes.latitude))+cos(radians($lat))*cos(radians(zipcodes.latitude))*cos(radians(zipcodes.longitude) - radians($lon)))) < $miles
AND profiles.zipcode = zipcodes.zipcode))";
Using that query to return results from my tables, I can return about 83 matches in 0.0715 ms.
Now, when I add "order by dist" to sort the results by the distance, the time it takes to return the same results (in order) jumps to about 0.1250 ms
The trouble is, there is no way to index the ORDER BY clause, because it is a formula, and the variables are constantly changing.
Is there no hope? Please Help!