mysql - 找出每组的最高 n 值

标签 mysql sql greatest-n-per-group

我遇到了与此相同的问题Finding the highest n values of each group in MySQL

我有一些这样的数据:

+ --------- + ----------- +
| lane      | series      |
+ --------- + ----------- +
| 1         | 680         |
| 1         | 685         |
| 1         | 688         |
| 2         | 666         |
| 2         | 425         |
| 2         | 775         |
+ --------- + ----------- +

And I'd like to grab the highest n series per lane (let's say 2 for the sake of this example, but it could be many more than that) So the output should be:

+ --------- + ----------- +
| lane      | series      |
+ --------- + ----------- +
| 1         | 688         |
| 1         | 685         |
| 2         | 775         |
| 2         | 666         |
+ --------- + ----------- +

I think the SQL with "funky" MySQL features are quite good.

set @count:=-1, @lane:=0; 
select lane, series
from (select lane, series from lane_series order by lane, series desc) x
where if(lane != @lane, @count:=-1, 0) is not null
and if(lane != @lane, @lane:=lane, lane) is not null
and (@count:=@count+1) < 2; -- Specify the number of row at top of each group here

令我惊讶的是,它在 MySQL 5.0 和 MySQL 5.1 上运行得很好,但在我的生产 MySQL 版本 MySQL 5.5 上却不起作用。

MySQL 5.5上的结果是这样的:

+ --------- + ----------- +
| lane      | series      |
+ --------- + ----------- +
| 1         | 688         |
| 1         | 685         |
+ --------- + ----------- +

请帮助我使其在 MySQL 5.5 上运行或告诉我为什么结果不同,非常感谢!

更新: 因为我的生产数据库中有大约 300 万条记录,所以我想知道如何快速、尽可能快地获取结果。

最佳答案

试试这个,也许它对你有用。

SELECT lane, series
FROM   tableA
WHERE (
        SELECT count(*)
        FROM   tableA AS f
        WHERE  f.lane = tableA.lane AND 
               f.series >= tableA.series
      ) <= 2
ORDER BY lane, series DESC

SQLFiddle Demo

关于mysql - 找出每组的最高 n 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12382009/

相关文章:

sql - Oracle SQL-在 "Distinct"查询中获取 "CASE"值

sql - 慢速选择 - PostgreSQL

python - 如何在django查询中获取每个人最近添加的记录

SQL如何选择某人发布的最新评论

php - 如何结合 REDIS 和 MySQL 进行批量插入以获得更好的性能(实时)

javascript - 如何将数据从 javascript 发送到 PHP 脚本

sql - 将记录从一个 MySQL 数据库传输到另一个

mysql - 如何消除列中相同值的重复?

mysql - 数据库挑战: How to Update 1 million records efficiently?

mysql - 查询显示年龄超过 18 岁且具有唯一城市的学生的学生表