将 SQL ALL 函数与 HAVING COUNT(*) >= 混淆

beg*_*lla 2 mysql sql

感谢您帮助理解使用 ALL 函数的查询结果的概念。提前致谢!

包含数据的示例表 = 下载员工表脚本 & 这是查询。

select salary, count(*)
from employees
group by salary
having count(*) >= ALL(SELECT count(*) from employees group by salary)
Run Code Online (Sandbox Code Playgroud)

我不明白为什么结果只返回 6 行,计数为 2。

这不应该having count(*) >= ALL(SELECT count(*) from employees group by salary) 匹配 select sub 和 return 行数 994 之间的每一行吗?

为什么会>=返回 6 行,而=or>返回 0 行?

如果能详细解释其背后的逻辑,我们将不胜感激。谢谢你!

Luk*_*zda 5

COUNT(*)子句中的关键点HAVING按每个组计算:

select salary, count(*)
from employees
group by salary
having count(*) >= ALL(SELECT count(*) from employees group by salary)
       -- this count changes per each salary
Run Code Online (Sandbox Code Playgroud)

这个查询很奇怪。让我们看一个总共 6 行的简单示例:

salary count  
100    3
200    1
300    2


-- per each group
3 >= ALL (3,1,2)   -- only this one will match
1 >= ALL (3,1,2) 
2 >= ALL (3,1,2)
Run Code Online (Sandbox Code Playgroud)

因此,您的查询将有效地返回薪水最高的行。

while = 或 > 返回 0 行?

-- always false for '=' or '>'
3 = ALL (3,1,2)
1 = ALL (3,1,2)
2 = ALL (3,1,2)
Run Code Online (Sandbox Code Playgroud)