一尘不染

提高MySQL查询性能-数学重查询

sql

有人愿意帮助我吗?在具有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)

阅读 142

收藏
2021-05-05

共1个答案

一尘不染

我认为这将为您提供所需的信息,而不管您关注的滚动日期范围…我已经通过创建带有两个标识列的自己的“发票”表进行了测试。使用@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个月。

2021-05-05