mysql limit inside group?

后端 未结 8 732
粉色の甜心
粉色の甜心 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:56

    Try placing the LIMIT clause after the GROUP BY clause.

    EDIT: Try this:

    SELECT * 
    FROM accounts a1
    WHERE 5 > 
    (
       SELECT COUNT(*)
       FROM accounts a2
       WHERE a2.type = a1.type
       AND a2.balance > a1.balance
    )
    

    This returns at most 5 accounts of each type with the biggest balances.

提交回复
热议问题