I have a quite simple Mysql query that outputs products from category ordered by price descending.
SELECT
p.id_product, p.price
FROM product p
INNER JOIN product_category pc
ON (pc.id_product = p.id_product AND pc.id_category=1234)
GROUP BY pc.id_product
ORDER BY p.price DESC
Since I have a lot of products in "product" table and even more product-category relations in "product_category" table this query lasts forever.
I have following indexes / primary keys defined:
- table "product" - primary key (id_product)
- table "product_category" - primary key (id_product, id_category), index(id_product), index(id_category)
But when I explain this query I get:
+----+-------------+-------+--------+--------------------+------------+---------+------------------------+-------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+--------------------+------------+---------+------------------------+-------+----------------------------------------------+
| 1 | SIMPLE | pc | index | PRIMARY,id_product | id_product | 4 | NULL | 73779 | Using index; Using temporary; Using filesort |
| 1 | SIMPLE | p | eq_ref | PRIMARY | PRIMARY | 4 | mydb.pc.id_product | 1 | |
+----+-------------+-------+--------+--------------------+------------+---------+------------------------+-------+----------------------------------------------+
so... Using temporary; Using filesort - I think that this is the problem why everything is running so slow.
Since this query is executed a lot of times from a closed-source software I can't change it. But I want to optimize table / indexes so this query will run faster. Any help appreciated.