Given is a table with 300\'000 test-records.
I need to do a select like this:
SELECT (SQRT(POWER(ABS(posts.latitude-$lat),2)+POWER(ABS(posts.longitude-$l
Actually you cannot optimize that query.
You are sorting the result using a calculated value, so you cannot use an index. If you use explain
you could see how your query in being executed, and using temporary
will be present in the extra
column, which means that all the data from your query is being stored on a temporary table in which the ordering is performed.
It doesn't matter if you only want the first 50 matches in the query, it has first to get all the data, dump it into a temporary table, sort the result in that table and then return to you the first 50 matches.
As you can suppose, this is a time and memory consuming operation.
So you best option is to place an index in the table to get all the rows you need as fast as you can and then process them with php
to get the data you need.
By the way, have a look to MySQL optimization guide.