mysql limit inside group?

后端 未结 8 639
粉色の甜心
粉色の甜心 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.

    0 讨论(0)
  • 2021-01-13 08:01

    Group by is used for aggregate functions (sums, averages...)

    Is allows you to split the aggregate result into groups. You have not used one of these functions.

    0 讨论(0)
提交回复
热议问题