MySQL-Performance when ordering on calculated column

China☆狼群 提交于 2019-12-02 08:44:48

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!