我有一张 table ;包含 2 个字段,name 和 salary。我使用下面的脚本找到了第三个最高薪水。
SELECT DISTINCT sal
FROM downtodate1.emp e1
WHERE 3 = (SELECT COUNT(DISTINCT sal) FROM downtodate1.emp e2 WHERE e1.sal<= e2.sal);
我想知道它是如何工作的,为什么这里使用 3?
最佳答案
select distinct sal
from downtodate1.emp AS e1
where 3 = (
select count(distinct sal)
from downtodate1.emp e2
where e1.sal <= e2.sal
);
假设您有一个这样的表:
sal
---
3
3
2
1
1
0
有了这部分
select distinct sal
from downtodate1.emp AS e1
你会得到结果
sal
---
3
2
1
0
这就是 4 个不同的薪水。
现在是子查询
select count(distinct sal)
from downtodate1.emp e2
where e1.sal <= e2.sal
对主查询中的每一行执行。它计算低于或等于主查询中行的不同值的数量。所以这个的结果实际上是(但没有显示):
sal | count(distinct sal) where e1.sal <= e2.sal
------------------------------------------------
3 1
3 1
2 2
1 3
1 3
0 4
与主查询不同,您将得到以下结果:
sal | count(distinct sal) where e1.sal <= e2.sal
------------------------------------------------
3 1
2 2
1 3
0 4
和 WHERE
条款3 = (/*subquery*/)
你只会得到
sal | count(distinct sal) where e1.sal <= e2.sal
------------------------------------------------
1 3
这一行。所以结果是1
.
希望现在一切都清楚了。
关于mysql - SQL中的第N个最大薪水查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15474216/