[Solved] MYSQL SUM until last day of Each month for last 12 months

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Use UNION ALL instead of UNION (query line: 66): Always use UNION ALL unless you need to eliminate duplicate records. By using UNION ALL, you'll avoid the expensive distinct operation the database applies when using a UNION clause.
Optimal indexes for this query:
ALTER TABLE `A` ADD INDEX `a_idx_date` (`date`);
ALTER TABLE `B` ADD INDEX `b_idx_type_id` (`type`,`id`);
The optimized query:
SELECT
        num2.last_dates,
        (SELECT
            SUM(amount) 
        FROM
            A 
        INNER JOIN
            B 
                ON A.B_id = B.id 
        WHERE
            B.type = 7 
            AND A.date <= num2.last_dates),
        (SELECT
            SUM(amount) 
        FROM
            A 
        INNER JOIN
            B 
                ON A.B_id = B.id 
        WHERE
            B.type = 5 
            AND A.date <= num2.last_dates) 
    FROM
        (SELECT
            last_dates 
        FROM
            (SELECT
                LAST_DAY(CURDATE() - INTERVAL CUSTOM_MONTH MONTH) last_dates 
            FROM
                (SELECT
                    1 CUSTOM_MONTH 
                UNION
                SELECT
                    0 
                UNION
                SELECT
                    2 
                UNION
                SELECT
                    3 
                UNION
                SELECT
                    4 
                UNION
                SELECT
                    5 
                UNION
                SELECT
                    6 
                UNION
                SELECT
                    7 
                UNION
                SELECT
                    8 
                UNION
                SELECT
                    9 
                UNION
                SELECT
                    10 
                UNION
                SELECT
                    11 
                UNION
                SELECT
                    12
            ) num
    ) num1
) num2 
ORDER BY
num2.last_dates

Related Articles



* original question posted on StackOverflow here.