astak16/blog-mysql

12 第二高的薪水

Opened this issue · 0 comments

题目

编写一个 SQL 查询,获取 employee 表中第二高的薪水(salary)。

create table employee (
	id int primary key auto_increment,
	salary int
);

insert into employee (salary) values(100),(200),(300);

SQL:方法一

select e.salary from (
	select
		salary,
		case when salary is not null then @rank:= @rank + 1 end as 排名
	from (select @rank:=0) as init, (
		select salary from employee group by salary order by salary desc
	) as t
) as e where e.排名 = 2;

解析

  • 先按照 salary 进行分组并且降序
  • 使用变量 @rank 计算出排名
  • 过滤出 排名 = 2 的数据

SQL:方法二

select salary from employee group by salary order by salary desc limit 1, 1;

解析

排序后使用 limit 截取第二条数据