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
worldtable 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:
- Create a temporary table (
qualifying_continents) that lists each eligible continent and its total population. - Join this temporary table to the main
worldtable using the sharedcontinentcolumn, 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.,
WHEREforIN, orFROM/JOINfor derived tables). Both approaches above fix this by clearly structuring the nested logic.
内容的提问来源于stack exchange,提问作者Danny




