我对需要返回在特定列上具有最大值的前 N 行的查询感到非常困惑.
I am really confused about the query that needing to return top N rows having biggest values on particular column.
例如,如果行 N-1, N, N + 1
具有相同的值.我必须返回 只返回前 N 行
或 前 N + 1
行.
For example, if the rows N-1, N, N + 1
have same values. Must I return just top N
or top N + 1
rows.
如果你这样做:
select *
from t
order by value desc
limit N
您将获得前 N 行.
如果你这样做:
select *
from t join
(select min(value) as cutoff
from (select value
from t
order by value
limit N
) tlim
) tlim
on t.value >= tlim;
或者您可以更简单地将其表述为:
Or you could phrase this a bit more simply as:
select *
from t join
(select value
from t
order by value
limit N
) tlim
on t.value = tlim.value;
以下是您在概念上想要执行的操作,但它可能不适用于 MySQL:
The following is conceptually what you want to do, but it might not work in MySQL:
select *
from t
where t.value >= ANY (select value from t order by value limit N)
这篇关于MySQL:选择前 n 个最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!