LeetCode #177第N高的薪水

https://leetcode-cn.com/problems/nth-highest-salary/description/

看起来好像是上一道题的延伸,感觉循环一波好像也能干,但是仔细一想,万一表的元组很多呢?

换个思路:先对表进行降序排序,然后查询前N个元组,最后从结果中再查询最后一个元组就是答案了。

limit 函数

  • 一个参数时代表查询数量
  • 两个参数时,第一个参数代表检索偏移量(从0开始),第二个参数代表查询数量
#查询按学号排序后学生表中的前四项数据(即第1-4行)
select * from Student order by SNO limit 4;
#查询按学号排序后学生表中的从第四项到最后一项的数据中的前两项(即排序表中的第4、5两行)
select * from Student order by SNO limit 4,2;

做法修改为:降序排序,查询第N行一直到最后一行,查询第一行。

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  declare m int;
  set m = N - 1;
  RETURN (
      # Write your MySQL query statement below.
      select Salary from Employee group by Salary order by Salary desc limit m,1
  );
END


猜你喜欢

转载自blog.csdn.net/a912952381/article/details/80732104