像这样的简单查询:
SELECT
products.*,
SUM(orderdetails.quantity) AS sold
FROM products
RIGHT JOIN orderdetails ON orderdetails.product_id = products.id
GROUP BY products.id, products.brand_id
ORDER BY sold DESC
如何更改它以获得每个品牌的两种产品?
答案 0 :(得分:1)
以下代码对您有所帮助,
SELECT ranked.*
FROM
(SELECT products.*,
@product_rank := IF(@current_brand = products.brand_id, @product_rank + 1, 1) AS product_rank,
@current_brand := products.brand_id
FROM ( SELECT
products.*,
SUM(orderdetails.quantity) AS sold
FROM products
JOIN orderdetails ON orderdetails.product_id = products.id
GROUP BY products.id, products.brand_id
ORDER BY products.brand_id,sold DESC
) products
) ranked
WHERE product_rank <= 2