【问题标题】:Confuse with SQL ALL function with HAVING COUNT(*) >=与 HAVING COUNT(*) >= 的 SQL ALL 函数混淆
【发布时间】:2019-12-28 14:37:21
【问题描述】:

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

带有数据的示例表 = download employee table script & 这里是查询。

select salary, count(*)
from employees
group by salary
having count(*) >= ALL(SELECT count(*) from employees group by salary)

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

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

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

对此背后的逻辑的详细解释将不胜感激。谢谢!

【问题讨论】:

标签: mysql sql


【解决方案1】:

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

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

这个查询很奇怪。让我们来看一个总共 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)

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

while = or > 返回 0 行?

-- always false for '=' or '>'
3 = ALL (3,1,2)
1 = ALL (3,1,2)
2 = ALL (3,1,2)

【讨论】:

  • 这有很大帮助.. 谢谢!
【解决方案2】:

单词 ALL 必须跟在比较运算符之后,意思是“如果子查询返回的列中的所有值的比较结果为 TRUE,则返回 TRUE。”

更多详情,请关注给定的网址:

https://dev.mysql.com/doc/refman/5.5/en/all-subqueries.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 2012-11-12
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多