MySQL world database Trying to avoid subquery

2019-06-01 16:20发布

问题:

I'm using the MySQL WORLD database.

For each Continent, I want to return the Name of the country with the largest population.

I was able to come up with a query that works. Trying to find another query that uses join only and avoid the subquery.

Is there a way to write this query using 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)

回答1:

This is the "greatest-n-per-group" problem that comes up frequently on 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;

Explanation: do a join looking for a country c2 that has the same continent and a greater population. If you can't find one (which is indicated by the outer join returning NULL for all columns of c2) then c1 must be the country with the highest population on that continent.

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.