链接:
点我进入leetcode
注意这个题目是因为有null值得情况得存在,也就是说如果只用一次select得话:
select salary as SecondHighestSalary from Employee order by salary desc limit 1 offset 1;
不过得测试用例如下:
发现这样查询返回的一行数据都没有,没有按照设想返回null,最后正确的结果如下,要在外层再套一次select,使用select null的思路即可实现。
正确答案为:
select ifNull(
(select distinct salary
from Employee
order by Salary Desc
limit 1,1),null
) as SecondHighestSalary;
为什么药这样呢?
是因为第一次查询后返回得可能是一个带列空表,第二次对空表得行进行查询才会返回null,在MySQL中,使用select null会返回null。
当然上述解法得另一个形式为:
select (select distinct salary from Employee order by salary desc limit 1 offset 1) as SecondHighestSalary;