我正在寻找一个更优雅的解决方案来解决与 GROUP BY 结合使用的 MySQL MIN() 问题。
我有两张桌子:
- 产品(id,group_id)
- product_attributes (product_id, attribute_id, value)
我希望从某个产品组的每个金属组(attribute_id = 40)中选择最便宜的金属。
以下查询有效,但我很确定它本来可以写得更好。
SELECT metal.product_id, metal.value AS `metal`, `price`.value AS `price`
FROM
product_attributes metal
INNER JOIN
(
SELECT metal.value AS `metal`, MIN(price.value) AS `price`
FROM
product_attributes metal
LEFT JOIN
product_attributes price
ON metal.product_id = price.product_id
INNER JOIN products p
ON p.id = metal.product_id
WHERE
metal.attribute_id = 40 AND
price.attribute_id = 37 AND
p.group_id = 1
GROUP BY
metal.value
ORDER BY metal ASC, price DESC
) AS d ON
d.metal = metal.value
LEFT JOIN
product_attributes price ON
metal.product_id = price.product_id AND price.attribute_id = 37
INNER JOIN
products p ON
p.id = metal.product_id
WHERE
metal.attribute_id = 40
AND d.price = price.value
AND p.group_id = 1
GROUP BY
metal.value
ORDER BY
metal.value ASC,
price.value DESC;