leetcode地址:https://oj.leetcode.com/problems/second-highest-salary/
這個問題很有趣,是要求我們寫個sql來查詢Employee表里第二高的工資,如果沒有第二高的,那么返回null。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
看到這個問題,可能很多人會想,這很簡單啊,寫個order by desc,然后找到第二個即可。
select Salary from Employee order by Salary desc limit 1,1
試試提交唄?Wrong answer,為什么?看條件約束啊,沒有第二要返回null,我看到null的第一直覺是通過join搞到null值,于是有了下面的ac sql:
select
max(Salary) as SecondHighestSalary
from(
select
o1.*
,case when o2.s is null then 1 else 0 end as nt
from
(select * from Employee)o1
left outer join
(select max(Salary) as s from Employee)o2
on(o1.Salary=o2.s)
)t
where nt=1
思路簡單說就是通過全表左外聯最大salary,從關聯不到的salary里再找最大不就是第二大嗎?
最后的結果是894ms,當然我堅信有很多更快更高效的結果。