我有一些不可能的请求:)。
我有一个表,其中一列名为 type
。我想为该列中的每种类型选择 3 条记录。这可能吗?
另请注意,我使用的是 MySQL 和 Sphinx。
更新: 表结构
id title type
1 AAAA string1
2 CCCC string2
3 EEEE string2
4 DDDD string2
5 FFFF string2
6 BBBB string2
6 BBBB string2
我希望我的 MySQL 返回的是(每种类型最多 3 条记录,按标题排序):
id title type
1 AAAA string1
6 BBBB string2
2 CCCC string2
4 DDDD string2
最佳答案
select id, title, type
from (select id, title, type,
@num := if(@group = type, @num + 1, 1) as row_number,
@group := type as dummy
from your_table
order by type, title) as x
where row_number <= 3
(在与 a different article 相同的网站上使用 Martin Wickman's answer !)
关于SQL - 每种类型只给我 3 次匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4775820/