简体   繁体   中英

Not able to find second highest salary from emp table without using limit and sub-query

SELECT
max(a.salary) as salary
FROM
tbl_emp as a,
tbl_emp as b
WHERE
a.salary < b.salary
and a.dept_Id = '57'
and a.Date_of_joining between '2015-01-01 00:00:00' and '2015-01-01 23:59:59';

This is just a visualization with rownum.

create table tbl_emp
(   id int auto_increment primary key,
    salary int not null,
    key(salary) -- with few rows, not used, run thru EXPLAIN cmd to prove it
);
insert tbl_emp(salary) values (1),(2),(3),(4),(5);  -- affordable employees

set @rownum:=0;
select * from
(
    select @rownum:=@rownum+1 as rownum,id,salary
    from tbl_emp
    order by salary desc
    limit 2
) xxx
where rownum=2;

+--------+----+--------+
| rownum | id | salary |
+--------+----+--------+
|      2 |  4 |      4 |
+--------+----+--------+

Probably you can do something like below using ORDER BY and LIMIT clause

SELECT
salary as secondHighest_salary
FROM
tbl_emp 
WHERE dept_Id = '57'
and Date_of_joining between '2015-01-01 00:00:00' and '2015-01-01 23:59:59'
ORDER BY salary desc
LIMIT 1,2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM