1. 程式人生 > >【Leetcode】Mysql查詢第二高的薪水

【Leetcode】Mysql查詢第二高的薪水

編寫一個 SQL 查詢,獲取 Employee 表中第二高的薪水(Salary) 。

+—-+——–+
| Id | Salary |
+—-+——–+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+—-+——–+
例如上述 Employee 表,SQL查詢應該返回 200 作為第二高的薪水。如果不存在第二高的薪水,那麼查詢應返回 null。

+———————+
| SecondHighestSalary |
+———————+
| 200 |
+———————+

# 這裡不描述union,not in
等方法,sql語句優化很重要 # 方法一:118ms, 從小於最高工資中找最高的工資,找出來就是第二高的工資 # select max(Salary) as SecondHighestSalary from Employee where Salary<(select max(Salary) from Employee)
# 方法二:
# 234ms,IFNULL,如果不為空返回第一個引數,為空返回null,降序後limit是關鍵,從第一條開始取,取一條,就是第二高工資
select IFNULL((select Distinct Salary from Employee order by
Salary DESC limit 1,1),null) as SecondHighestSalary