如何找到列的第n个最高值?

diE*_*cho 10 mysql

是否有类似于的命令:

  • 2nd highest salary from tbl_salary 要么

  • 4th highest salary from tbl_salary

我见过:

select salary
from tbl_salary t
where &n = (
    select count(salary) 
    from(
        select distinct salary
        from tbl_salary
    )where t.salary<=salary
);
Run Code Online (Sandbox Code Playgroud)

它是如何工作的?

有没有其他简单的方法来获得结果?

nic*_*ckf 14

如果是基本查询,那么只需使用LIMIT:

-- get the 4th highest salary
SELECT salary FROM tbl_salary
ORDER BY salary DESC
LIMIT 3,1
Run Code Online (Sandbox Code Playgroud)

  • @nickf,我通过执行上述查询获得第五名!"限制3,1"将获得第四名,我是对的吗?请指教 (3认同)

小智 7

select * from employee order by salary desc limit 1,1
Run Code Online (Sandbox Code Playgroud)

说明: limit x,y

  • x:要从中开始显示记录的行偏移量.对于第n个记录,它将是n-1.
  • y:要显示的记录数.(在这种情况下总是1)


小智 6

//表格的最高薪水

select salary from table order by salary desc limit 0,1
Run Code Online (Sandbox Code Playgroud)

//第二高薪

select salary from table order by salary desc limit 1,1
Run Code Online (Sandbox Code Playgroud)

使用此查询,您可以从表中获得第n个薪水....