2013-03-04 109 views
-4

我想從員工表中打印第n個最高工資關於MySQL查詢的說明

查詢是:

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 

雖然它的工作好,我無法解釋它是如何工作的。任何人都可以對此有所瞭解嗎?

+0

我看起來很奇怪這個'(n-1)'爲什麼有 – 2013-03-04 11:08:28

+0

這裏有些東西缺失,例如變量n。 – aurbano 2013-03-04 11:09:36

+0

它應該是'n'而不是'n-1' – 2013-03-04 11:11:28

回答

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 
) 
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) 

對於外部查詢中的每個記錄,子查詢都返回同一個表上具有較高(或等於第二個版本)值的所有不同薪水值的計數;外部查詢中的相等條件將確保只選擇匹配數量更高的工資的記錄。

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