mysql 分几组 每组查几条

表结构 users

typetitlecreated_at
a花开花下12022-02-14 00:26:01
a花开花落22022-02-14 00:28:01
a开心麻花32022-02-14 00:30:01
a开心啦哈42022-02-14 00:32:01
a开心摸哈52022-02-14 00:34:01
b他的故事62022-02-14 00:36:01
b大海卡的72022-02-14 00:36:01
b大海故事82022-02-14 00:34:01
b大海声音92022-02-14 00:34:01
b大海哈哈102022-02-14 00:34:01
c故事开始112022-02-14 00:39:01

试例

根据 type 每类根据时间排序取 3

1
2
3
4
5
6
7
8
9
10
11
select number, type, title, created_at
from (select @type := '', @number := 0) as rcin
join (select @number := IF(type != @type, 1, @number + 1) as number,
@type := type,
title,
type,
created_at
from users
order by type, created_at desc) as nrcircirci
where number <= 3
order by created_at desc, number

参考资料