You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

SQL嵌套查询:如何将子查询结果用于外层SELECT(SQLZoo第9题)

Solution to SQLZoo Nested Query Problem (Question 9)

Hey Danny, great job getting the subquery right that identifies continents with total population under 250 million! Let's break down how to nest that into a main query to get the country-level data you're after.

Approach 1: Use IN with a Nested Subquery

Your existing subquery returns the list of qualifying continents—we can use that to filter the main world table directly with the IN operator:

SELECT name, continent, population
FROM world
WHERE continent IN (
    -- Your original subquery here
    SELECT continent
    FROM world
    GROUP BY continent
    HAVING SUM(population) < 250000000
);

How this works:

  • The inner subquery runs first, outputting all continents where the total population of its countries adds up to less than 250 million.
  • The outer query then selects every country from the world table that belongs to one of those continents.

Approach 2: Join with a Derived Table

If you prefer using joins (which can be more efficient in some cases), you can turn your subquery into a derived table and join it to the main world table on the continent field:

SELECT w.name, w.continent, w.population
FROM world w
JOIN (
    SELECT continent, SUM(population) AS total_continent_pop
    FROM world
    GROUP BY continent
    HAVING total_continent_pop < 250000000
) qualifying_continents ON w.continent = qualifying_continents.continent;

Here, we:

  1. Create a temporary table (qualifying_continents) that lists each eligible continent and its total population.
  2. Join this temporary table to the main world table using the shared continent column, which filters down to only countries in those continents.

Why Your Earlier Attempt Might Have Failed

If you tried something like SELECT A.continent..., you probably forgot to either:

  • Assign an alias to your subquery and reference it correctly, or
  • Use the subquery in the right clause (e.g., WHERE for IN, or FROM/JOIN for derived tables). Both approaches above fix this by clearly structuring the nested logic.

内容的提问来源于stack exchange,提问作者Danny

火山引擎 最新活动