力扣刷题学习SQL篇——1-13 第二高的薪水(可以使用子查询/LIMIT子句)

该博客介绍了如何在LeetCode的SQL题目中找出第二高的薪水。当不存在第二高薪水时,返回null。文章讨论了三种解题方法,包括使用子查询和LIMIT子句,并提到了IFNULL函数的用法来处理可能的空值情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

力扣刷题学习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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值