MySQL会两次计算相同的SUM吗?

时间:2013-11-21 14:56:31

标签: mysql sql

我们假设我有这样的查询:

SELECT Sum(imp)                  AS totalimp, 
       Sum(money)                AS totalmoney, 
       ( Sum(money) / Sum(imp) ) AS result 
FROM   table 
GROUP  BY date 

MySQL会缓存两个总和,还是会计算SUM(imp)和SUM(money)两次?

如果没有,有没有办法避免MySQL重新计算两次总和?

谢谢!

2 个答案:

答案 0 :(得分:0)

SELECT @totalimp := Sum(imp) AS totalimp, 
       @totalmoney := Sum(money) AS totalmoney, 
       ( @totalmoney / @totalimp ) AS result 
FROM   table 
GROUP  BY date 

答案 1 :(得分:0)

怎么样

SELECT @totalimp := x.totalimp, 
   @totalmoney := x.totalmoney, 
   @result := ( x.totalmoney / x.totalimp )
FROM   (SELECT Sum(imp) AS totalimp, 
           Sum(money) AS totalmoney
         FROM   table 
         GROUP  BY date ) x