I\'m wanting to optimize a query using a union as a sub query. Im not really sure how to construct the query though. I\'m using MYSQL 5
Here is the original query:>
SELECT Parts.id
FROM (
SELECT parts_id
FROM Parts_Category
WHERE Parts_Category.category_id = '508'
UNION
SELECT parts_id
FROM Parts_Category
WHERE Parts_Category.main_category_id = '508'
) pc
JOIN Parts
ON parts.id = pc.parts_id
AND Parts.status = 'A'
LEFT JOIN
Image
ON image.id = parts.image_id
Note that MySQL
can use Index Merge
and you can rewrite your query as this:
SELECT Parts.id
FROM (
SELECT DISTINCT parts_id
FROM Parts_Category
WHERE Parts_Category.category_id = '508'
OR Parts_Category.main_category_id = '508'
) pc
JOIN Parts
ON parts.id = pc.parts_id
AND Parts.status = 'A'
LEFT JOIN
Image
ON image.id = parts.image_id
, which will be more efficient if you have the following indexes:
Parts_Category (category_id, parts_id)
Parts_Category (main_category_id, parts_id)