力扣刷题学习SQL篇——1-13 第二高的薪水(可以使用子查询/LIMIT子句)
1、题目
题目链接:https://leetcode.cn/problems/second-highest-salary/
SQL架构
Create table If Not Exists Employee (id int, salary int)
Truncate table Employee
insert into Employee (id, salary) values ('1', '100')
insert into Employee (id, salary) values ('2', '200')
insert into Employee (id, salary) values ('3', '300')
Employee 表:
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id 是这个表的主键。
表的每一行包含员工的工资信息。
编写一个 SQL 查询,获取并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null 。
查询结果如下例所示。
示例 1:
输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
示例 2:
输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null |
+---------------------+
2、解法
解法1:
我的想法是先将最高工资剔除掉,然后获取的新表在查个最高工资。这样第二工资就出来啦。这里就算有空值也不要紧,因为新表里面没数据max(salary)返回也是null
select max(salary) SecondHighestSalary from
(select id , salary from Employee where salary != (select max(salary) salary from Employee)) ee
解法2:
按照降序排列,默认是从0开始,我这里要选第二高,所以limit之后要先写1,然后要一条数据,所以后面也是1。看上去好像解决了,但是如果这个表只有1条数据,那么就没有数据了就是空的了。但是题目要求没有第二高工资的情况下SecondHighestSalary要返回null。
所以下面这种不行
错误示范:
# 错误示范
select distinct salary SecondHighestSalary from Employee order by salary desc limit 1,1
既然如此,那么我们把他当成一个临时表从中获取数据
正确示范:
# 正确示范
select (select distinct salary from Employee order by salary desc limit 1 , 1) SecondHighestSalary
解法三:
关于ifnull的使用可以看知识补充,就是一个判断是否为空的函数。
select ifnull(
(select distinct salary SecondHighestSalary from Employee order by salary desc limit 1,1) , null) SecondHighestSalary
知识补充
limit的使用
select * from tableName limit i,n
# tableName:表名
# i:为查询结果的索引值(默认从0开始),当i=0时可省略i
# n:为查询结果返回的数量
# i与n之间使用英文逗号","隔开
#
limit n 等同于 limit 0,n
IFNULL(expr1,expr2)
如果expr1不是 NULL, 则IFNULL()返回 expr1;否则返回 expr2。
mysql> SELECT IFNULL(1,0);
-> 1
mysql> SELECT IFNULL(NULL,10);
-> 10
mysql> SELECT IFNULL(1/0,10);
-> 10
mysql> SELECT IFNULL(1/0,'yes');
-> 'yes'