组内的mysql限制?

omg*_*omg 5 mysql sql

我想限制组内记录的大小,这是我的试用版,如何做到对不对?

mysql> select * from accounts limit 5 group by type;
Run Code Online (Sandbox Code Playgroud)

错误1064(42000):您的SQL语法有错误; 检查与MySQL服务器版本对应的手册,以便在第1行的"按类别分组"附近使用正确的语法

dna*_*irl 5

聚合函数(以及它需要的GROUP BY)的要点是将许多行转换为一行.因此,如果您真的只想要前5个储蓄账户和前5个支票账户以及前5个美元账户等,您需要的更像是:

条件:account_balance的特定帐户类型的前5位

SELECT account_type, account_balance FROM accounts WHERE account_type='savings' 
   ORDER BY account_balance DESC LIMIT 5
UNION
SELECT account_type, account_balance FROM accounts WHERE account_type='chequing' 
   ORDER BY account_balance DESC LIMIT 5
UNION
SELECT account_type, account_balance FROM accounts WHERE account_type='USD' 
   ORDER BY account_balance DESC LIMIT 5;
Run Code Online (Sandbox Code Playgroud)

它并不漂亮,但如果您使用脚本构造SQL,则在account_types中进行子搜索并将查询连接在一起是很简单的.


Ada*_*ott 5

我使用编号的行有一些运气:

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;
Run Code Online (Sandbox Code Playgroud)

这将给你2个结果item_type.(一个问题:确保你重新运行前两个set语句,否则你的行号将逐渐变得越来越高,row_number < 3限制将无效.

我从几个 帖子中拼凑出来,这些帖子已经在SO上的其他答案中联系起来了.


Joh*_*ett 0

Group by 用于聚合函数(求和、平均值...)

允许您将聚合结果分成几组。您还没有使用过这些功能之一。