以下代码片段使用 MySQL 变量技巧为每个 CID 的每一行分配一个数字。为了使示例简单,我将返回的行数限制为每个 CID 2 个。
select cid
, qid
, text
from (
select if(@last_cid = cid, @rn := @rn + 1, @rn := 1) as rn
, (@last_cid := cid)
, cid
, qid
, text
from YourTable yt
cross join
(select @rn := 0, @last_cid := -1) r
) as SubQueryAlias
where rn < 3;
数据设置:
create table YourTable (QID int, TEXT varchar(50), CID int);
insert YourTable values
(1, 'hi', 1),
(1, 'hi', 1),
(2, 'hi', 1),
(2, 'hi', 1),
(3, 'hi', 2),
(4, 'hi', 2),
(4, 'hi', 2),
(5, 'hi', 3);
每个 CID 最多返回两行:
+------+------+------+
| cid | qid | text |
+------+------+------+
| 1 | 1 | hi |
| 1 | 1 | hi |
| 2 | 3 | hi |
| 2 | 4 | hi |
| 3 | 5 | hi |
+------+------+------+