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 query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null. +---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+ https://leetcode.com/problems/second-highest-salary/description/ solution: 本想找第二高的就是子查詢找到 兩個最高的 而後取最小的那個 select Salary as SecondHighestSalary from (select * from Employee order by Salary desc limit 2) temp order by Salary asc limit 1 可是執行 告訴我結果是錯的 原來題目的要求中沒有第二高的就返回 null 看來轉換思路很重要呀,當時想按照上面的方式 怎麼處理子查詢只有一條的狀況呀 真是陷入了本身的坑 而後按照取到max最大的,從比最大的小中的最大的,若是我要取第三大的 是否是比較坑 SELECT MAX(Salary) as SecondHighestSalary FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee); 而後去看看網上的大神都是怎麼處理的 這邊UNION ALL 和 UNION是同樣的吧 SELECT Salary as SecondHighestSalary FROM Employee GROUP BY Salary UNION ALL (SELECT NULL AS SecondHighestSalary) ORDER BY SecondHighestSalary DESC LIMIT 1,1; 若是是我 mysql估計就會卡在這邊怎麼處理null的問題出不來了 SELECT Salary as SecondHighestSalary FROM Employee GROUP BY Salary DESC LIMIT 1,1 下面這個max的用法 和上面的殊途同歸 SELECT MAX(Salary) as SecondHighestSalary FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee); 後面這我的寫的真直接呀 SELECT MAX(Salary) as SecondHighestSalary FROM Employee E1 WHERE 1 = (SELECT COUNT(DISTINCT(E2.Salary)) FROM Employee E2 WHERE E2.Salary > E1.Salary);
git地址:https://github.com/woshiyexinjie/leetcode-xinmysql