Limit number of rows per id in a SQL query

mysql, sql

Solution

Adapting from another answer

  set @brand_id= '';
  set @num = 0;

  select
  products.id, products.brand_id,
  @num := if(@brand_id= brand_id, @num + 1, 1) as dummy_1,
  @brand_id:= brand_id as dummy_2,
  @num as row_number
  from products
  where brand_id IN ('1', '2','3')
  group by
  brand_id,
  row_number
  having row_number <= 10;

Problem

I want to limit the results of 10 products for each brand_id. Here's how my query looks like: ``` SELECT products.id, products.brand_id FROM products JOIN ( select id, brand_id from products limit 10) pinner ON products.id = pinner.id WHERE pinner.brand_id IN ('1', '2','3') ; ``` That obviously does not work. Any suggestions? EDIT: This post helped me with the solution: http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

Original source

Related problems