我要求在产品详细信息页面中显示类似产品,以便列出的产品应以分层方式与当前产品属性匹配,如下所示
- 尺寸、颜色、类别、公司应与当前产品匹配
- 尺寸、颜色、类别应与当前产品匹配
- 尺寸、颜色应与当前产品相匹配
- 尺寸应与当前产品匹配
我的 sql 查询如下所示:
(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 - 当前产品 ID 和状态表示可用!
有没有办法优化上述查询?
注意 需要输出:我们需要 10 个类似的产品。如果有 4 个符合条件 1 的产品,则需要先随机列出。同样,我们需要在其下方列出符合其他条件的产品。
提前致谢!