编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
Id | Salary |
---|---|
1 | 100 |
2 | 200 |
3 | 300 |
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
SecondHighestSalary |
---|
200 |
分析
首先看到这个题目,最先想到的是查询最高的薪水,只需要降序排序,然后取出最上面的一条记录就行了(select distinct Salary from Employee order by desc limit 1
),那么第二高的薪水只需要进行偏移量1的操作就可以了(select distinct Salary as SecondHighestSalary from Employee order by desc limit 1 offset 1
)
但是,当记录只有一条时,上面的解法就会出错,而不会返回null
将其作为临时表,再进行选择一次就可以获得正确的结果
select
(select distinct Salary from Employee order by Salary desc limit 1 offset 1 )
as SecondHighestSalary
或者使用 “IFNULL” 函数
select
ifnull((select distinct Salary from Employee order by Salary desc limit 1 offset 1), null)
as SecondHighestSalary
总结: 合理利用已知的方法来解决现有的问题,同时还要考虑解法可能出现的问题。