MySQL query slow because of ORDER BY with Stored Functions

Deadly 提交于 2019-12-14 03:16:58

问题


My query goes from 15 seconds to 0.05 seconds when I remove the ORDER BY in the following query:

simplified version:

SELECT field1, fiedl2, field 3,  
    FUNC1(1, 2) AS score1,  
    FUNC2(1, 2) AS score2,  
    FUNC3(1, 2) AS score3,  
    FUNC4(1, 2) AS score4  
FROM table  
WHERE field1 = 1  
ORDER BY (score1 * 1 + score2 * 2 + score3 * 2 + score4 * 4) DESC;

I have a couple of stored functions that calculate sub-scores. Except I have to order the result based on the total score. In the ORDER BY I use * 2 to add some weight to the subscores to influence the total score.

I use MySQL 5.6.13

Has anybody has an idea how I can make the ORDER BY, but not slow it down? Like is it possible to and store the score# fields and sum them up?

Thanks!


回答1:


The difference in time is because MySql needs to create a sorted temp table and fill it with data. As your query is running much slower when using order by, the problem might be in disk where temp data is stored. You haven't mentioned how many rows you are returning from this query. You may also try manually perform the steps that MySql is probably doing, so create a temp table with primary key (order_by_result int, n int auto_increment) and insert into it your select results:

Insert into t(order_by_result, n, ...)
select (score1 * 1 + score2 * 2 + score3 * 2 + score4 * 4),null,...

and check hpw fast it runs - you may also check this way if the problem lies in your storage.




回答2:


You could add a total_score column to the table, and define a trigger to update it automatically whenever a row is added or updated. Then index the column, and ORDER BY total_score should be fast.




回答3:


I think the best solution is to precalculate the values of the functions and store them in the database. This way, the problem of calculating the values of the function on the fly will be transformed into a very simple ordering query.

As lowleveldesing has said, this type of queries forces mysql to calculate the product (score1 * 1 + score2 * 2 + score3 * 2 + score4 * 4) for all the register before giving you any output.



来源:https://stackoverflow.com/questions/19638949/mysql-query-slow-because-of-order-by-with-stored-functions

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