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                 |
+---------------------+

本题主要考察SQL中limit和offset的用法。以下列出比较简洁的两种解法:

Select
    (Select Distinct Salary
    From Employee
    Order By Salary Desc
    Limit 1 Offset 1) AS SecondHighestSalary
SELECT 
  CASE 
  WHEN COUNT(DISTINCT(Salary)) <= 1 THEN null 
  ELSE  (select salary from employee order by salary desc limit 1, 1)
  END 
AS SecondHighestSalary 
FROM Employee 

两种解法刚好涵盖了limit的两种用法,两种用法区别如下:

① select * from table limit 2 offset 1;      

//含义是从第1条(不包括)数据开始取出2条数据,limit后面跟的是2条数据,offset后面是从第1条开始读取,即读取第2,3条

② select * from table limit 2,1;                 

//含义是跳过2条取出1条数据,limit后面是从第2条开始读,读取1条信息,即读取第3条数据