我正在尋找一種更優雅的解決方案,以解決與MySQL MIN()與GROUP BY一起使用時遇到的問題。SQL MIN()&GROUP BY
我有兩個表:
- 產品(ID,GROUP_ID)
- product_attributes(產品,attribute_id,值)
我希望選擇最便宜的金屬從各金屬組(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;