I've a requirement to show the similar products in product detail page in such a way that the products listed should match the current product properties in a hierarchical way as given below
- Size, color, category, company should match with the current product
- Size, color, category should match with the current product
- Size, color should match with the current product
- Size should match with the current product
My sql query is as given below:
(SELECT pd.product_id, pd.name, p.price
FROM mg_product_description pd
JOIN `mg_product` p ON p.product_id = pd.product_id
WHERE
pd.size_id = '33' AND
pd.color_id = '2' AND
pd.category_id = '3' AND
pd.company_id = '1' AND
pd.product_id != '53' AND
p.status = '1'
ORDER BY RAND() LIMIT 10
)
UNION
(SELECT pd.product_id, pd.name, p.price
FROM mg_product_description pd
JOIN `mg_product` p ON p.product_id = pd.product_id
WHERE
pd.size_id = '33' AND
pd.color_id = '2' AND
pd.category_id = '3' AND
pd.product_id != '53' AND
p.status = '1'
ORDER BY RAND() LIMIT 10
)
UNION
(SELECT pd.product_id, pd.name, p.price
FROM mg_product_description pd
JOIN `mg_product` p ON p.product_id = pd.product_id
WHERE
pd.size_id = '33' AND
pd.color_id = '2' AND
pd.product_id != '53' AND
p.status = '1'
ORDER BY RAND() LIMIT 10
)
UNION
(SELECT pd.product_id, pd.name, p.price
FROM mg_product_description pd
JOIN `mg_product` p ON p.product_id = pd.product_id
WHERE
pd.size_id = '33' AND
pd.product_id != '53' AND
p.status = '1'
ORDER BY RAND() LIMIT 10
)
53 - current product id and status denotes available!
Is there any way to optimize the above query?
Note Output required: We need 10 similar products. If there exists 4 products matching condition 1, then they need to listed at first in random order. Similarly we need to list the products matching other conditions below it.
Thanks in Advance!