问题:
力扣原题链接:
https://leetcode-cn.com/problems/second-highest-salary/
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
分析:
①先找到最高的元素
②再找出只低于①中找到元素的数据
SQL语句:
分步求
① select max(salary) from employee
② select max(distinct Salary) from employee where Salary < ①
考虑可能没有找到并进行整合
select
(select max(distinct Salary) from employee where Salary < (select max(salary) from employee)
) SecondHighestSalary
第二种方法:
先按照薪水降序排序,找到第二个元素,再使用ifnull来做一个非空判断,同时使用limit来找到元素,此处可以扩展为找到第N高的元素
select ifnull((select distinct e.salary SecondHighestSalary from employee e order by e.salary desc limit 1, 1),null) SecondHighestSalary
使用limit此处有这两种写法,原理是分页的原理,数据库的索引是从0开始的
①直接用是从第1个索引开始,找到1个元素
limit 1,1
②这样子写的话是取1个元素,从索引1开始
limit 1 offset 1