增加MySQL查询性能 - 数学繁重的查询

时间:2012-01-11 00:43:29

标签: mysql sql performance optimization

有谁愿意帮我这个?在具有10000行的MEMORY表上,以下查询大约需要18秒。如果我没有“where”约束,则只需不到一分钟。我已经打开了查询缓存,并将其作为预备语句进行尝试。有什么我能做的吗?索引还是什么不是?

SELECT SQL_CACHE
date(todaydata.postdate) as postdate,
SUM(CASE when todaydata.amount > 0 THEN todaydata.amount ELSE 0 END) AS INFLOW,
SUM(CASE when todaydata.amount < 0 THEN todaydata.amount ELSE 0 END) AS OUTFLOW
FROM invoice as todaydata
LEFT JOIN invoice as yesterdaydata ON todaydata.postdate=DATE_ADD(yesterdaydata.postdate,interval -1 day)
where todaydata.postdate between now() - interval 2 month and now() + interval 1 month
GROUP BY date(todaydata.postdate)

2 个答案:

答案 0 :(得分:3)

我认为这会得到你想要的东西,但是你关注的滚动日期范围...我已经通过创建我自己的“发票”表进行测试,其中列出了两列。利用可以在查询中内联使用的@ mySQL变量实际上非常简单...唯一的事情是,现在有了真正的方法来了解什么是“开放”平衡,所以我设置了初始值启动值为零,然后从那里调整。

踢球者是“PreAgg”查询,只是根据输入/输出的日期进行汇总。然后,通过按日期顺序对结果进行排序,@ sql变量启动。

select
      PreAgg.PostDate,
      @PrevBal as BegBal,
      PreAgg.OutFlows,
      PreAgg.InFlows,
      @PrevBal := @PrevBal + PreAgg.OutFlows + PreAgg.InFlows as EndBal
   from 
      ( select
              i.postdate,
              sum( if( i.amount < 0, i.amount, 0 ) ) as OutFlows,
              sum( if( i.amount > 0, i.amount, 0 ) ) as InFlows
           from 
              invoice i
           where
              i.postdate between date_sub( now(), interval 2 month )
                             and date_add( now(), interval 1 month )
           group by
              i.postdate
           order by 
              i.postdate ) as PreAgg,
      ( select @PrevBal := 0.00 ) as SqlVars

然而,即使我已经给了3个月的窗口(-2个月,+ 1个月),我认为这真的没有意义,因为未来的帖子还没有发生......可能更多重要的是要有

       where
          i.postdate > date_sub( now(), interval 3 month )

将从当前日期/时间开始过去3个月。

答案 1 :(得分:0)

  1. LEFT JOIN转为INNER JOIN
  2. 您最好使用Memcached而不是MySQL缓存。