此题为【LeetCode数据库】——第二高的薪水(176)拔高版本,二者使用的数据表和其中的记录均相同。
一、题目
编写一个 SQL 查询,获取 Employee
表中第二高的薪水(Salary
) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述Employee
表,N = 2
时,应返回第二高的薪水200
。如果不存在第N
高的薪水,那么查询应返回NULL
。
+------------------------+
| getNthHighest(2) |
+------------------------+
| 200 |
+------------------------+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/nth-highest-salary/
二、解答
由于本题要求可以根据不同的N都能查出相应的结果,故应当使用MySQL的自定义函数来实现,关于如何自定义并使用MySQL函数请见【MySQL进阶】——自定义函数和存储过程入门。
mysql> delimiter $$
mysql> create function getNthHighest(n int(11)) returns int(11)
-> begin
-> declare nthHighest int(11);
-> set n = n - 1;
-> set nthHighest = (select Salary from Employee group by Salary order by Salary desc limit n, 1);
-> return nthHighest;
-> end
-> $$
Query OK, 0 rows affected (0.01 sec)
mysql> delimiter ;
mysql> select getNthHighest(2);
+------------------+
| getNthHighest(2) |
+------------------+
| 200 |
+------------------+
3 rows in set (0.00 sec)
mysql> select getNthHighest(5);
+------------------+
| getNthHighest(5) |
+------------------+
| NULL |
+------------------+
3 rows in set (0.00 sec)