SQL - 每种类型只给我 3 次匹配

标签 sql mysql sphinx greatest-n-per-group

我有一些不可能的请求:)。

我有一个表,其中一列名为 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/

相关文章:

sql - PostgreSQL : How do I take multiple rows with values in different columns and combine into one row with all the values on one line?

php - 如何在sql中设计群聊通知?

php mysql 全文搜索 : lucene, sphinx,或者?

sql - 在 Neo4j 中创建节点之间的关系时 ServiceUnavailable

mysql - 想不通的sql错误

PHP mySQL - UNIX_TIMESTAMP 不等于 strtotime

mysql - 如何通过忽略前两个字符来从下面的重复记录中获取唯一记录的列表?

mysql - 显示日期之间的数据并循环遍历年份

elasticsearch - 使用Sphinx进行多语言全文搜索

由于缺少 searchd.pid,centos 7 上的 sphinx 无法启动