求指导,Mysql 7天查询,超时

MySql 码拜 8年前 (2016-05-11) 876次浏览
sql语句:
select appid,  sum(ordermoney) summoney
,sum(case when startdatetime>=”2016-07-18″ and startdatetime<“2016-07-19″ then ordermoney else 0 end)  as  day1
,sum(case when startdatetime>=”2016-07-19” and startdatetime<“2016-07-20″ then ordermoney else 0 end)  as  day2
,sum(case when startdatetime>=”2016-07-20” and startdatetime<“2016-07-21″ then ordermoney else 0 end)  as  day3
,sum(case when startdatetime>=”2016-07-21” and startdatetime<“2016-07-22″ then ordermoney else 0 end)  as  day4
,sum(case when startdatetime>=”2016-07-22” and startdatetime<“2016-07-23″ then ordermoney else 0 end)  as  day5
,sum(case when startdatetime>=”2016-07-23” and startdatetime<“2016-07-24″ then ordermoney else 0 end)  as  day6
,sum(case when startdatetime>=”2016-07-24” and startdatetime<“2016-07-25″ then ordermoney else 0 end)  as  day7
from cashorder_tb force index(ix_cash_000000_tb_startdatetime)
where startdatetime>=”2016-07-18” and startdatetime<“2016-07-25”
group by appid
order by summoney desc
limit 10;
表的数据量大致300w条,
表的appid, startdatetime也都单独做了索引
这样查询出来,时间多达7s, 已经超时了。
另外explain了这条语句, 原因是加了force index,所以走的startdatetime字段索引, 但是不加,走的却是appid的字段索引。
求指导,需要怎么样优化才能降低查询时间? 谢谢
解决方案

20

你是先聚合求和,然后再选择前10行,所以 速度快慢和你startdatetime>=”2016-07-18″ and startdatetime<“2016-07-25”  时间段呃逆,有多少数据有关系,假如这段时间内的数据量非常大,那么索引起到的作用就相对小,假如这段时间内的数据较少,例如就1000来条,那么速度应该还能更快。
建议改进索引,试试创建复合索引,包含3个字段: startdatetime,appid,ordermoney

10

考虑1楼的复合索引建议,另外,你这个统计是按天的,可以考虑建个STORED的计算列,这样可以直接基于天做统计,对于大量数据会更有效

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明求指导,Mysql 7天查询,超时
喜欢 (0)
[1034331897@qq.com]
分享 (0)