select count(name),continent
from world
where population <= 25000000
group by continent
当我在世界表上运行以下查询时,会出现以下结果
COUNT(NAME) ; CONTINENT
===================================
26 ; North America
**17 ; Oceania**
7 ; South America
41 ; Europe
42 ; Africa
24 ; Asia
我再次运行了以下查询
select count(name)
from world
group by continent
出现以下结果
COUNT(NAME) ; CONTINENT
===================================
29 ; North America
**17 ; Oceania**
12 ; South America
49 ; Europe
54 ; Africa
42 ; Asia
将这些视为两个表,我试图提取具有共同count(name)
我运行此查询的值
select count(name),continent
来自世界各地 按大陆分组 有计数(姓名)在( 从人口&lt; = 25000000 group by continent)的世界中选择计数(名称)
导致
COUNT(NAME) ; CONTINENT
================================
17 ; Oceania <--------- thought I will get only this row
42 ; Asia
现在又一次运行了这个查询
select count(name),continent from world where population <= 25000000 group by continent having count(name) in (select count(name) from world group by continent )
COUNT(NAME) ;CONTINENT
===============================
17 ; Oceania
42 ; Africa
我在结果集中遇到了亚洲和非洲的问题
但我怎样才能过滤它们 假设我正在使用MY SQl
(对我来说,作为一个绝对的初学者并原谅我的错误编辑无法帮助它)
答案 0 :(得分:0)
当你跑步时:
SELECT count(name), continent FROM world
WHERE population <= 25000000 GROUP BY continent
您正在选择人口少于250米的国家/地区数量。大洋洲和非洲都包含在这些行中。
COUNT(NAME) ; CONTINENT
===================================
26 ; North America
**17 ; Oceania**
7 ; South America
41 ; Europe
42 ; Africa
24 ; Asia
接下来执行:
HAVING count(name) in (SELECT count(name) FROM world GROUP BY continent)
即。仅包含在结果集的COUNT(NAME)列中找不到COUNT(NAME)的数字且没有WHERE的行。 Oceania
在两个结果集中都有17个,因此包括在内。 Africa
在第一个(WHERE)结果集中有COUNT(NAME)=42
。使用您的HAVING子句,它会与您的第二个结果集中的Asia
匹配。
因此我们显示两行:
COUNT(NAME) ; CONTINENT
===================================
17 ; Oceania
42 ; Africa
这可能是您想要的(请注意添加的WHERE
):
SELECT count(worldA.name) as cnt, worldA.continent FROM world worldA
WHERE worldA.population <= 25000000 GROUP BY worldA.continent
HAVING cnt in
(SELECT count(worldB.name) FROM world worldB
WHERE worldB.continent = worldA.continent
GROUP BY worldB.continent);