我遇到了与此相同的问题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/