MySQL-Performance when ordering on calculated column

后端 未结 2 1064
傲寒
傲寒 2021-01-23 17:08

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         


        
相关标签:
2条回答
  • 2021-01-23 17:20

    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.

    0 讨论(0)
  • 2021-01-23 17:28

    Make the column for $userParam an index, that way the query will perform faster. Or you could create an indexed view: http://www.codeproject.com/Articles/199058/SQL-Server-Indexed-Views-Speed-Up-Your-Select-Quer

    Hope this helps

    0 讨论(0)
提交回复
热议问题