mysql limit inside group?

后端 未结 8 760
粉色の甜心
粉色の甜心 2021-01-13 07:35

I want to limit the size of records inside a group, and here is my trial, how to do it right?

mysql> select * from accounts limit 5 group by type;
         


        
8条回答
  •  误落风尘
    2021-01-13 07:58

    I've had some luck with using numbered rows:

    set @type = '';
    set @num = 0;
    
    select
      items.*,
      @num := if(@type = item_type, @num + 1, 1) as dummy_1,
      @type := item_type as dummy_2,
      @num as row_number
    from items
    group by
      item_type,
      row_number
    having row_number < 3;
    

    This will give you 2 results per item_type. (One gotcha: make sure you re-run the first two set statements otherwise your row numbers will steadily get higher and higher and the row_number < 3 restriction won't work.

    I pieced this together from a couple of posts which have been linked in other answers on SO.

提交回复
热议问题