题目
编写一个 sql 查询,获取 employee
表中第二高的薪水(salary) 。
+----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 employee
表,sql查询应该返回 200
作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null
。
+---------------------+ | secondhighestsalary | +---------------------+ | 200 | +---------------------+
解决方案
方法一:使用子查询
和 limit
子句
将不同的薪资按降序排序,然后使用 limit
子句获得第二高的薪资。
select distinct salary as secondhighestsalary from employee order by salary desc limit 1 offset 1;
然而,如果没有这样的第二最高工资,这个解决方案将被判断为 “错误答案”,因为本表可能只有一项记录。为了克服这个问题,我们可以将其作为临时表。
select (select distinct salary from employee order by salary desc limit 1 offset 1) as secondhighestsalary;
方法二:使用 ifnull
和 limit
子句
解决 “null” 问题的另一种方法是使用 “ifnull” 函数,如下所示。
select ifnull( (select distinct salary from employee order by salary desc limit 1 offset 1), null) as secondhighestsalary;
摘自: