mysql limit inside group?

后端 未结 8 655
粉色の甜心
粉色の甜心 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 08:00

    This will probably do the trick, although if type isn't indexed, it'll be sloooowwww. And even with one, it's not especially fast:

    SELECT a.*
    FROM accounts a
         LEFT JOIN accounts a2 ON (a2.type = a.type AND a2.id < a.id)
    WHERE count(a2.id) < 5
    GROUP BY a.id;
    

    A better bet would be to just order the list by type and then use a loop at the business layer to remove the rows you don't want.

提交回复
热议问题