176. Second Highest Salary

来源:互联网 发布:windows微信登录 编辑:程序博客网 时间:2024/06/06 00:07

闲着没事到LeetCode上做做SQL的题目,结果被卡了半天。

Write a SQL query to get the second highest salary from the Employee table.

+—-+——–+
| Id | Salary |
+—-+——–+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+—-+——–+

For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return null.

翻译一下,表Employee的结构像上面这样,查询表里Salary次高的那个,如果查不到就返回NULL。

就是这个返回null卡了我半天,我想查不到默认返回不就是null么,于是我写了这样的SQL :
select Salary as SecondHighestSalary order by Salary desc limit 1,1;
结果过不了,返回的结果是空,而不是NULL。

那就加一个默认值吧,如果为空就返回默认值,那就是IFNULL函数了:
select IFNULL(Salary, null) as SecondHighestSalary order by Salary desc limit 1,1;
结果还是不可以,返回仍为空,经过上网仔细查询一番因为order by Salary desc limit 1,1;返回的是空,语句到这里就结束了,所以select后面紧跟的函数没有执行。

知道了原因,最终版本终于可以了:
SELECT IFNULL((SELECT distinct Salary FROM Employee order by Salary desc limit 1,1) ,null) as SecondHighestSalary;

理解可能有误,望大家指出理解错误之处,多谢。

1 0
原创粉丝点击