1

我正在使用 MySQL WORLD数据库。

对于每个大陆,我想返回人口最多的国家的名称。

我能够提出一个有效的查询。试图找到另一个只使用连接的查询并避免子查询。

有没有办法使用 JOIN 编写此查询?

SELECT Continent, Name
FROM Country c1
WHERE Population >= ALL (SELECT Population FROM Country c2 WHERE c1.continent = c2.continent);

+---------------+----------------------------------------------+
| Continent     | Nanme                                         |
+---------------+----------------------------------------------+
| Oceania       | Australia                                    |
| South America | Brazil                                       |
| Asia          | China                                        |
| Africa        | Nigeria                                      |
| Europe        | Russian Federation                           |
| North America | United States                                |
| Antarctica    | Antarctica                                   |
| Antarctica    | Bouvet Island                                |
| Antarctica    | South Georgia and the South Sandwich Islands |
| Antarctica    | Heard Island and McDonald Islands            |
| Antarctica    | French Southern territories                  |
+---------------+----------------------------------------------+
11 rows in set (0.14 sec)
4

1 回答 1

5

这是 StackOverflow 上经常出现的“greatest-n-per-group”问题。

SELECT c1.Continent, c1.Name
FROM Country c1
LEFT OUTER JOIN Country c2
  ON (c1.continent = c2.continent AND c1.Population < c2.Population)
WHERE c2.continent IS NULL;

解释:做一个连接,寻找一个c2拥有相同大陆和更多人口的国家。如果您找不到一个(由为 的所有列返回 NULL 的外连接指示c2),那么c1必须是该大陆上人口最多的国家。

Note that this can find more than one country per continent, if there's a tie for the #1 position. In other words, there could be two countries for which no third country exists with a greater population.

于 2009-11-28T20:58:18.013 回答