我想限制组内记录的大小,这是我的试用版,如何做到对不对?
mysql> select * from accounts limit 5 group by type;
Run Code Online (Sandbox Code Playgroud)
错误1064(42000):您的SQL语法有错误; 检查与MySQL服务器版本对应的手册,以便在第1行的"按类别分组"附近使用正确的语法
聚合函数(以及它需要的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中进行子搜索并将查询连接在一起是很简单的.
我使用编号的行有一些运气:
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上的其他答案中联系起来了.
| 归档时间: |
|
| 查看次数: |
14064 次 |
| 最近记录: |