You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL如何查询最低工资员工及同最高薪资的第二名员工姓名

SQL查询问题:获取最低工资员工及最高薪资第二名员工信息

业务背景

现有odd_empcop员工表,表内最低工资为2000,最高工资为8000,存在多名员工领取最高薪资8000。需求为查询领取最低工资的员工信息,以及领取最高薪资的第二名员工的信息。

初始实现代码

(select emp_name, salary from odd_empcop
where salary = (select min(salary) from odd_empcop
                    order by salary ))
union
(select  emp_name, salary from odd_empcop
where salary = (select max(salary) from odd_empcop
    
                order by salary desc ));

初始运行输出

emp_name salary
Gautham  2000
Melinda  8000
Cory     8000
Vikram   8000

预期输出

emp_name salary
Gautham  2000
Cory     8000

问题原因

初始写法的第二个查询子句匹配了所有薪资等于最高值的员工,没有做条数限制和偏移,所以返回了全部3位最高薪员工的记录,不符合只取最高薪第二名的需求。

最终正确实现代码

(select emp_name, salary from odd_empcop
where salary = (select min(salary) from odd_empcop
                    order by salary ))
union
(select  emp_name, salary from odd_empcop
where salary = (select max(salary) from odd_empcop

                order by salary desc ) limit 1,1);

逻辑说明

新增的limit 1,1语法作用是对符合最高薪条件的结果集,跳过第一条记录,取后续的1条,刚好对应需求中最高薪资群体里排序后的第二名员工。

内容的提问来源于stack exchange,提问作者Naive

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:18:00