How to optimize a query in mysql when using group by clause?

I use the following query, which takes about 52 seconds if grouped by a "supervisor", otherwise it completes within 2 or 3 seconds:

SELECT SQL_CALC_FOUND_ROWS MONTHNAME(o.sale_on) AS DATE,
       SUM(od.current_status_id=1) AS sales,
       IFNULL(SUM(CASE WHEN od.current_status_id=2
                  OR od.current_status_id=3 THEN
                   (SELECT SUM(amount)
                    FROM order_refund_chargeback
                    WHERE order_detail_id = od.order_detail_id) END),0) AS total_outflow,
       IFNULL(
               (SELECT GROUP_CONCAT(CONCAT(user_first_name," ",user_last_name))
                FROM user_detail
                WHERE user_id IN
                  (SELECT manager_id
                   FROM `user_org_map`
                   WHERE user_id = o.assigned_to)),"") AS supervisor,
       IFNULL(mco.country_name,"") AS country
FROM orders o
RIGHT JOIN order_detail od
    USING (order_id)
LEFT JOIN user_detail ud
    ON ud.user_id = o.assigned_to
LEFT JOIN customer_detail cd
    ON cd.customer_id= o.customer_id
LEFT JOIN master_product mp
    ON mp.product_id = od.product_id
LEFT JOIN master_campaign mc
    ON mc.campaign_id = cd.campaign_id
LEFT JOIN master_country mco
    ON mco.country_id = cd.country
WHERE 1=1
 AND YEAR(o.sale_on) =2015
GROUP BY supervisor
ORDER BY supervisor ASC
LIMIT 0, 12

Any suggestion on how to optimize this to reduce time?

+4
source share
1 answer

Do not use the date function in the where clause because you cannot take advantage of the potential help of the index. Instead of the condition, YEAR(o.sale_on) =2015use the condition:

o.sale_on BETWEEN '2015-01-01' AND '2015-12-31'.  
0
source

Source: https://habr.com/ru/post/1612377/


All Articles