sea*_*zxx 2 mysql sql greatest-n-per-group
我遇到了与此相同的问题.查找MySQL中每个组的最高n值
我有一些这样的数据:
+ --------- + ----------- + | lane | series | + --------- + ----------- + | 1 | 680 | | 1 | 685 | | 1 | 688 | | 2 | 666 | | 2 | 425 | | 2 | 775 | + --------- + ----------- +
而且我想要获得每个泳道最高的n系列(假设这个例子比较说2,但它可能比这更多)所以输出应该是:
+ --------- + ----------- + | lane | series | + --------- + ----------- + | 1 | 688 | | 1 | 685 | | 2 | 775 | | 2 | 666 | + --------- + ----------- +
我认为具有"时髦"MySQL功能的SQL非常好.
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
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,它在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
Run Code Online (Sandbox Code Playgroud)