MySQL世界数据库试图避免子查询

Yad*_*ada 1 mysql sql greatest-n-per-group

我正在使用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)
Run Code Online (Sandbox Code Playgroud)

Bil*_*win 5

这是StackOverflow上频繁出现的"每组最大"问题.

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;
Run Code Online (Sandbox Code Playgroud)

说明:进行联接以查找c2具有相同大陆和更多人口的国家/地区.如果找不到一个(由外部联接指示为所有列返回NULL c2),则c1必须是该大陆上人口最多的国家/地区.

请注意,如果排名第一,那么每个大洲可以找到多个国家/地区.换句话说,可能有两个国家没有第三个国家,人口更多.