mstraczkowski
mstraczkowski

Reputation: 69

MySQL - Slow query optimization

I have a problem optimizing a really slow prestashop SQL query (mysql takes about 3.5 seconds to get the result).

Query:

SELECT
    SQL_CALC_FOUND_ROWS a.*, a.id_order AS id_pdf, 
    CONCAT(LEFT(c.`firstname`, 1), '. ', c.`lastname`) AS `customer`, 
    osl.`name` AS `osname`, 
    os.`color`, 
    IF((SELECT COUNT(so.id_order) FROM `ps_orders` so WHERE so.id_customer = a.id_customer) > 1, 0, 1) as new, 
    (SELECT COUNT(od.`id_order`) FROM `ps_order_detail` od WHERE od.`id_order` = a.`id_order` GROUP BY `id_order`) AS product_number 
FROM `ps_orders` a 
LEFT JOIN `ps_customer` c 
    ON (c.`id_customer` = a.`id_customer`) 
LEFT JOIN `ps_order_history` oh 
    ON (oh.`id_order` = a.`id_order`) 
LEFT JOIN `ps_order_state` os 
    ON (os.`id_order_state` = oh.`id_order_state`) 
LEFT JOIN `ps_order_state_lang` osl 
    ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = 6) 
WHERE 1 
    AND oh.`id_order_history` = (SELECT MAX(`id_order_history`) FROM `ps_order_history` moh WHERE moh.`id_order` = a.`id_order` GROUP BY moh.`id_order`) 
ORDER BY `date_add` DESC
LIMIT 0,50

EXPLAIN Result:

EXPLAIN Result

What should I do ?

Thanks in advance for the answers.

Upvotes: 3

Views: 782

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269933

This is a bit long for a comment.

The explain looks reasonable. Except. The final order by is requiring a filesort on 204,480 rows, which is probably accounting for much of the time. It is unclear where the column date_add is coming from. But, perhaps you know that all rows will come from the last week or so. If so, then an additional where clause might help:

where date_added >= now() - interval 7 day and . . .

Upvotes: 2

Related Questions