Skip to content

Latest commit

 

History

History
44 lines (30 loc) · 1.26 KB

176. 第二高的薪水(简单).md

File metadata and controls

44 lines (30 loc) · 1.26 KB

[TOC]

1 原题目

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

2 解法

解法1select MAX(Salary) as SecondHighestSalary FROM Employee where Salary < (Select MAX(Salary) from Employee);

解法2select  ifnull ((select distinct Salary from Employee order by Salary desc limit 1,1),null)as SecondHighestSalary ;

3 知识扩展

简单的联合查询

  • 解法1:能解决问题,但不是根本办法。(求第三或者第四呢?)
  • 解法2:显然第二种方法更为符合原题思路,扩展也只需要改变Limit的参数。
  • ifnull(value1,value2)。如果value1不为空,结果返回value1,如果value1为空,结果返回value2
  • Limit x 返回多少条数据 limit x,y 从第X+1条开始,返回y条。