简体   繁体   中英

Make mysql query faster

I have this query which takes around 29 second to perform and need to make it faster. I have created index on aggregate_date column and still no real improvement. Each aggregate_date has almost 26k rows within the table. One more thing the query will run starting from 1/1/2018 till yesterday date

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在此处输入图片说明

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. 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. 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'

The index on aggregate_date column is not useful for performance because in not involved in where condition
looking to your code an useful index should be on column 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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