SQL结合了SELECT语句

ha9*_*3ar 6 sql subquery

这实际上来自一个交互式网站SQLzoo.net,我用它来刷新我的SQL知识.

问题是

查找所有国家/地区人口<= 25000000的大陆.然后查找与这些大洲相关联的国家/地区的名称.显示名称,大陆和人口.

我做了什么来制作解决方案

SELECT name, continent, population 
FROM world x 
WHERE population <= ALL(SELECT population 
                        FROM world y 
                        WHERE y.continent = x.continent 
                          AND population > 25000000)
Run Code Online (Sandbox Code Playgroud)

我不想复制和编辑输出,因为它非常繁琐 - 可以通过进入本页的第7号来检查 - http://www.sqlzoo.net/wiki/SELECT_within_SELECT_Tutorial

我想知道我写错了什么.我做了其他问题没问题,但这个问题似乎有点棘手(或者可能是比我想象的更多嵌套的SELECT查询).

任何建议/解释表示赞赏.

wil*_*ser 9

SELECT name, continent, population 
FROM world w
WHERE NOT EXISTS (                  -- there are no countries
   SELECT *
   FROM world nx
   WHERE nx.continent = w.continent -- on the same continent
   AND nx.population > 25000000     -- with more than 25M population 
   );
Run Code Online (Sandbox Code Playgroud)

更新删除零(两次)


小智 9

以下代码对我有用:

SELECT name, continent, population FROM world x
  WHERE 25000000>=ALL (SELECT population FROM world y
                         WHERE x.continent=y.continent
                         AND population>0)
Run Code Online (Sandbox Code Playgroud)


Gor*_*off 6

我写了很长很长时间的SQL,几乎从不使用ALL,SOME或者ANY.

对我来说,编写此查询的明显方法是使用窗口函数:

SELECT name, continent, population 
FROM (SELECT w.*, MAX(population) OVER (PARTITION BY continent) as maxpop
      FROM world w
     ) w
WHERE maxpop < 250000000;
Run Code Online (Sandbox Code Playgroud)

如果你不喜欢这样的解决方案,使用一个明确的joinaggregation:

SELECT name, continent, population 
FROM world w JOIN
     (SELECT continent
      FROM world
      GROUP BY continent
      HAVING max(pop) < 250000000
     ) c
     ON w.continent = c.continent;
Run Code Online (Sandbox Code Playgroud)


小智 5

我写了这个,它奏效了。当我使用给定的条件时,它变得复杂了,所以我使用了否定。如果一个大陆至少有一个国家的人口超过 2500 万,您会希望从选择中跳过它。您的第二个选择不遵循此逻辑。因此错误。

它是这样的:

select name,continent,population from world
where not continent in
(select distinct continent from world where population >25000000)
Run Code Online (Sandbox Code Playgroud)

上面的代码获取至少有一个人口超过 2500 万的国家的大陆,并且首先选择获取所有不来自该大陆的国家。如果您注意到我们不必再次检查人口,因为所有国家/地区的人口显然都少于或等于 2500 万。


小智 5

SELECT name, continent, population 
FROM world x 
WHERE 25000000 > ALL(SELECT population 
                     FROM world y 
                     WHERE y.continent = x.continent 
                     )
Run Code Online (Sandbox Code Playgroud)

'ALL'部分比较了一个大陆上有2500万人口的所有国家的人口,如果小于2500万,它将打印出该区域所有国家的人口名称。