select 每个品牌的前 2 畅销产品

select top 2 bestseller products from each brands

像这样的简单查询:

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

如何更改为每个品牌只能获得两个产品?

以下代码会对您有所帮助,

 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

SqlFiddle Demo Here