mysql查询工资前十名_MYSQL查询以找到薪水第n高的所有员工

bd96500e110b49cbb3cd949968f18be7.png

The two tables are salary_employee and employee

employee_salary

salary_id emp_id salary

Employee

emp_id | first_name | last_name | gender | email | mobile | dept_id | is_active

Query to get the all employees who have 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 any better and optimized way we can query this,

2) Is using LIMIT an good option

3) We have more options to calculate the nth highest salary, which is the best and what to follow and when?

One option using :

SELECT *

FROM employee_salary t1

WHERE ( N ) = ( SELECT COUNT( t2.salary )

FROM employee_salary t2

WHERE t2.salary >= t1.salary

)

Using Rank 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

解决方案

This is too long for a comment.

You have asked what seems like a reasonable question. There are different ways of doing things in SQL and sometimes some methods are better than others. The ranking problem is just one of many, many examples. The "answer" to your question is that, in general, order by is going to perform better than group by in MySQL. Although even that depends on the particular data and what you consider to be "better".

The specific issues with the question are that you have three different queries that return three different things.

The first returns all employees with a "dense rank" that is the same. That terminology is use purposely because it corresponds to the ANSI dense_rank() function which MySQL does not support. So, if your salaries are 100, 100, and 10, it will return two rows with a ranking of 1 and one with a ranking of 2.

The second returns different results if there are ties. If the salaries are 100, 100, 10, this version will return no rows with a ranking of 1, two rows with a ranking of 2, and one row with a ranking of 3.

The third returns an entirely different result set, which is just the salaries and the ranking of the salaries.

My comment was directed at trying the queries on your data. In fact, you should decide what you actually want, both from a functional and a performance perspective.


版权声明:本文为weixin_30229479原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。