Mysql:在limit前面加distinct

今天刷牛客,遇到一道sql题是这样的

获取当前(to_date='9999-01-01')薪水第二多的员工的emp_no以及其对应的薪水salary
CREATE TABLE `salaries` (
`emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`from_date`));

我的答案(已通过测试----->也就是正确的意思)

select emp_no,distinct salary
from salaries 
where to_date='9999-01-01' 
order by salary desc limit 1,1

有瑕疵,因为没有考虑到薪水第二多的员工有多人

评论区标准答案:

select emp_no, salary from salaries
where to_date = '9999-01-01' 
and salary = (
select distinct salary
from salaries
order by salary desc limit 1,1)

有人会想,limit已经取一条数据了,为什么还要加distinct

评论区一张截图解决:
Mysql:在limit前面加distinct_第1张图片
也就是说,这样写,取的是去重之后的数据

你可能感兴趣的:(mysql)