从表中选择第3个最大值

时间:2013-08-06 08:12:34

标签: php mysql

我有一张名为“薪水”的表。

  user_id salary
    1          100
    2          200
    3          500
    4          500
    5          500
    6          700
    7          800
    8          700
    9          800 

我需要从这张桌子中找出第三高的薪水。有时候不止一张记录会出现在桌子上。如何写查询? plesae帮帮我

3 个答案:

答案 0 :(得分:4)

如果你需要获得 3d最高工资值,在你的情况下500你可以做

SELECT salary 
  FROM salary
 GROUP BY salary 
 ORDER BY salary DESC
 LIMIT 2, 1

输出:

| SALARY |
----------
|    500 |

这是 SQLFiddel 演示

获取薪水等于第三高的所有记录

SELECT * 
  FROM salary
 WHERE salary = 
(
  SELECT salary 
    FROM salary
   GROUP BY salary 
   ORDER BY salary DESC
   LIMIT 2, 1
)

输出:

| USER_ID | SALARY |
--------------------
|       3 |    500 |
|       4 |    500 |
|       5 |    500 |

这是 SQLFiddel 演示

答案 1 :(得分:1)

使用:

SELECT * FROM salary ORDER BY salary DESC LIMIT 2,1

答案 2 :(得分:1)

这也是另一种选择

SELECT distinct salary 
FROM salary
ORDER BY salary DESC
LIMIT 2, 1

选择所有记录:

select * from salary where salary = (
    SELECT distinct salary 
    FROM salary
    ORDER BY salary DESC
    LIMIT 2, 1
)