简体   繁体   English

使mysql查询更快

[英]Make mysql query faster

I have this query which takes around 29 second to perform and need to make it faster.我有这个查询需要大约 29 秒来执行并且需要使它更快。 I have created index on aggregate_date column and still no real improvement.我已经在aggregate_date 列上创建了索引,但仍然没有真正的改进。 Each aggregate_date has almost 26k rows within the table.每个aggregate_date 在表中有近26k 行。 One more thing the query will run starting from 1/1/2018 till yesterday date查询将从 2018 年 1 月 1 日开始运行到昨天的另一件事

select MAX(os.aggregate_date) as lastMonthDay,
       os.totalYTD
from (
    SELECT aggregate_date,
           Sum(YTD) AS totalYTD
    FROM tbl_aggregated_tables
    WHERE subscription_type = 'Subcription Income'
    GROUP BY aggregate_date
) as os
GROUP by MONTH(os.aggregate_date), YEAR(os.aggregate_date);

I used Explain Select ... and received the following我使用了 Explain Select ... 并收到了以下内容在此处输入图片说明

update更新

The most of query time is consumed by the inner Query, so as scaisEdge suggested bellow i have tested the query and the time is reduced to almost 8s.大部分查询时间被内部查询消耗,所以正如 scaisEdge 建议的那样,我已经测试了查询,时间减少到近 8 秒。 the Inner Query will look like:内部查询将如下所示:

select agt.aggregate_date,SUM(YTD) 
      from tbl_aggregated_tables as agt
      FORCE INDEX(idx_aggregatedate_subtype_YTD)
      WHERE agt.subscription_type = 'Subcription Income'
      GROUP by agt.aggregate_date

I have noticed that this comparison "WHERE agt.subscription_type = 'Subcription Income'" takes the most of time.我注意到这种比较“WHERE agt.subscription_type = 'Subcription Income'”花费了大部分时间。 So is there any way to change that and to be mentioned the column of subscription_type only have 2 values which is 'Subcription Income' and 'Subcription Unit'那么有什么方法可以改变这一点,需要提到的是,subscription_type 列只有 2 个值,即“订阅收入”和“订阅单位”

The index on aggregate_date column is not useful for performance because in not involved in where condition aggregate_date列上的索引对性能没有帮助,因为不涉及 where 条件
looking to your code an useful index should be on column subscription_type查看您的代码,一个有用的索引应该在列subscription_type

you could try using a redundant index adding also the column involved in select clause (for try to obtain all the data in query from index avoiding access to table)so you index could be您可以尝试使用冗余索引添加 select 子句中涉及的列(尝试从索引获取查询中的所有数据,避免访问表),因此您的索引可能是

create idx1 on tbl_aggregated_tables (subscription_type, aggregate_date, YTD )

the meaning of the last group by seems not coherent with the select clause最后一个 group by 的意思似乎与 select 子句不一致

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM