【问题标题】:Clarification on the MySQL query [closed]澄清MySQL查询[关闭]
【发布时间】:2013-02-18 10:42:58
【问题描述】:

我想从雇员表中打印第 n 个最高工资

查询是:

SELECT *
FROM emp E1
WHERE
  (n-1) = (SELECT count(distinct(E2.salary))
           FROM emp E2 Where
           E2.salary< E1.salary)
ORDER BY
  E1.salary ASC

虽然效果很好,但我无法解释它是如何工作的。有人能说明一下吗?

【问题讨论】:

  • 我看起来很奇怪这个(n-1)为什么会有
  • 这里缺少一些东西,例如变量n。
  • 应该是n 而不是n-1
  • 这永远行不通,我不知道他说它是如何工作的,
  • 就目前而言,它将返回第 n 个最低的工资记录,而不是第 n 个最高的工资记录;否则,它应该可以工作。

标签: mysql database join


【解决方案1】:

可能更容易理解为:

select * From emp E1 
where n = 1 + 
         (select count(distinct E2.salary) 
          from emp E2 
          Where E2.salary > E1.salary)

或:

select * From emp E1 
where n =(select count(distinct E2.salary) 
          from emp E2 
          Where E2.salary >= E1.salary)

对于外部查询中的每条记录,子查询返回同一张表上所有不同工资值的计数,这些值具有更高(或在第二个版本中)值;然后,外部查询中的相等条件确保只选择匹配 n 更高薪水数字的记录。

原始查询中的order by 是不必要的。

【讨论】:

    【解决方案2】:

    这是 MYSQL 中的一个特性。

    如果你有一个基本的查询,你可以使用 LIMIT

    -- get the 9th highest salary
    SELECT salary FROM tbl_salary
    ORDER BY salary DESC
    LIMIT 9,1
    

    如果是复杂查询,则使用

    -- get the 9th highest salary
    select distinct(salary) from tbl_salary e1
    where 9 = (
    select count(salary) 
    from tbl_salary e2
    where e1.salary< e2.salary
    )
    

    【讨论】:

      猜你喜欢
      • 2015-12-20
      • 2012-11-09
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多