关于分组的MySQL混淆。为什么会这样?

时间:2013-08-29 08:01:35

标签: mysql sql

为什么三个查询如此不同?根据MySQL文档,他们不应该做同样的事情吗?

select cc, max(c) as "Most Official Billingual Count" from (
  select CountryCode as cc, count(*) as c from countrylanguage where isofficial = "T"
  group by cc
) t group by cc

以此格式返回多行:CountryCode Official_Language_Count_Blabla

而如果我删除一个组...

select cc, max(c) as "Most Official Billingual Count" from (
  select CountryCode as cc, count(*) as c from countrylanguage where isofficial = "T"

) t group by cc

它会返回第一个国家/地区代码以及总计数: ABW 238

而且:

select cc, max(c) as "Most Official Billingual Count" from (
  select CountryCode as cc, count(*) as c from countrylanguage where isofficial = "T"
  group by cc
) t 

将返回类似这样的内容:ABW 4

我对这整个群体非常困惑。

内部查询

  select CountryCode as cc, count(*) as c from countrylanguage where isofficial = "T

应该返回所有国家/地区代码并计算重复的代码吗?对?但它没有那样做。看起来我必须先做第一个队列来获得理想的效果,这对我来说非常困惑

1 个答案:

答案 0 :(得分:1)

您的子查询:

select CountryCode as cc, count(*) as c from countrylanguage where isofficial = "T"
除非您没有按照相应的标准对记录进行分组,否则

没有任何意义。您需要对记录进行分组,因为WHERE子句仅指示选择条件。请参阅此clarifying video(DBMS是Oracle,但无论如何)了解GROUP BY。另外(我更喜欢阅读),您可以找到许多文章,例如this

因此,如果您需要在计数之间找到MAX,则需要先在子查询中通过GROUP BY组合您的组。