优化/替代此自引用更新查询

时间:2012-03-07 09:42:16

标签: php mysql sql optimization

我有这个更新查询:

UPDATE aggregate_usage_input t 
       JOIN (SELECT t2.id 
             FROM   aggregate_usage_input t2 
             WHERE  t2.is_excluded_total_gallons = 0 
                    AND t2.is_excluded_cohort = 0 
                    AND t2.is_excluded_outlier = 0 
             ORDER  BY t2.occupant_bucket_id, 
                       t2.residence_type_bucket_id, 
                       t2.reading_year, 
                       t2.nthreading, 
                       t2.total_gallons)t_sorted 
         ON t_sorted.id = t.id 
SET    t.rownum = @rownum := @rownum + 1 

根据排序更新rownum字段(实际上是按字段排序)。

选择查询需要9秒,因为我们使用顺序是可以接受的。

此查询的更新部分需要很长时间。在400.000记录表上超过5分钟。我们需要在一分钟左右的时间内减少这种情况。

如何加快速度,或者您有其他方法可以解决此问题?

1 个答案:

答案 0 :(得分:0)

子查询会让你慢下来。在实践中,我注意到将子查询分成临时表或表变量更快。

尝试:

CREATE TEMPORARY TABLE Temp (id int);

INSERT INTO Temp
SELECT t2.id 
FROM   aggregate_usage_input t2 
WHERE  t2.is_excluded_total_gallons = 0 
    AND t2.is_excluded_cohort = 0 
    AND t2.is_excluded_outlier = 0 
ORDER  BY t2.occupant_bucket_id, 
    t2.residence_type_bucket_id, 
    t2.reading_year, 
    t2.nthreading, 
    t2.total_gallons;

UPDATE aggregate_usage_input t
JOIN Temp t_sorted
     ON t_sorted.id = t.id 
SET t.rownum = @rownum := @rownum + 1 
相关问题