Two tables: employee_employee and employee
employee_salary
salary_id emp_id salary
Employee
emp_id | first_name | last_name | gender | email | mobile | dept_id | is_active
A request to get all employees who have the nth highest salary, where n = 1,2,3, ... any integer
SELECT a.salary, b.first_name
FROM employee_salary a
JOIN employee b
ON a.emp_id = b.emp_id
WHERE a.salary = (
SELECT salary
FROM employee_salary
GROUP BY salary
DESC
LIMIT 1 OFFSET N-1
)
My questions:
1) Is there a better and optimized way that we can request,
2) Uses LIMIT is a good option
3) We have more opportunities to calculate the nth highest salary, which is the best and what should be observed and when?
One option:
SELECT *
FROM employee_salary t1
WHERE ( N ) = ( SELECT COUNT( t2.salary )
FROM employee_salary t2
WHERE t2.salary >= t1.salary
)
Using the ranking method
SELECT salary
FROM
(
SELECT @rn := @rn + 1 rn,
a.salary
FROM tableName a, (SELECT @rn := 0) b
GROUP BY salary DESC
) sub
WHERE sub.rn = N
user3752338
source
share