Consider the following query:
SELECT *
FROM product_related pr
LEFT JOIN product p ON (pr.related_id = p.product_id)
LEFT JOIN product_to_store p2s ON (p.product_id = p2s.product_id)
WHERE
pr.product_id = '" . (int)$product_id . "' AND
p.status = '1' AND
p.date_available <= NOW() AND
p2s.store_id = '0'
Tables structure:
product_related
- 2 int columns, both indexed. 10 partitions by HASH(product_id). 1.2m records. Total table size 30mb.
product
- 48 various columns (excluding large text/blobs). Column product_id
is primary and indexed. Columns status
and date_available
are also indexed. 10 partitions by HASH(product_id). 130k records. Total table size 61mb.
product_to_store
- 2 int columns, index PRIMARY(product_id, store_id). No partitions. 130k records. Total table size 3.4mb.
Most of the times the query performs fast, under 0.05s. But occasionally it slows to 30..50s. If you visit the affected page for the second time (basically just hit F5 right away) - the query again performs fine under fractions of second.
I've met this behavior earlier, with different tables, on other websites, but I can't figure out where is the flaw.
EXPLAIN
Version
Stats
Delay
product
product_related
product_to_store
So question: how to optimize occasionally slow query where all indexes are set and tables are partitioned?