MySQL world database Trying to avoid subquery

别等时光非礼了梦想. 提交于 2019-12-06 17:56:24

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!