Employee 表:
±------------±-----+
| Column Name | Type |
±------------±-----+
| id | int |
| salary | int |
±------------±-----+
id 是这个表的主键。
表的每一行包含员工的工资信息。
输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null |
+---------------------+
select max(salary) SecondHighestSalary from employee
where salary<(select max(salary) from employee);
limit n子句表示查询结果返回前n条数据
offset n表示跳过x条语句
limit y offset x 分句表示查询结果跳过 x 条数据,读取前 y 条数据
按道理下面的语句就足够了,注意需要distinct去重。
select distinct salary from employee order by salary desc
limit 1 offset 1
此时如果不存在第二大的数据不会返回null.
所以使用ifnull。
ifnull(a,b)函数解释:如果a不为空,结果返回a;如果a是空,结果返回b
select ifnull((select distinct salary from employee order by salary desc
limit 1 offset 1),null) as SecondHighestSalary;
对于求第几大的数据limit显然更具有可扩展性。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/second-highest-salary