将mysql子查询转换为Join

时间:2013-08-04 09:09:47

标签: mysql join subquery

我是mysql&的新手刚开始学习它。昨晚我试图在世界数据库的国家/地区表上重新形成以下子查询,进入连接。

SELECT continent, NAME, population FROM country c WHERE
population = (SELECT MAX(population) FROM country c2 
WHERE c.continent=c2.continent AND population > 0)

我尝试跟随查询和其他几个内部联接等但失败了。我得到的结果是以下查询,其中最大人口数量与预期相同,但是大陆&国名不同。

SELECT c.continent, c2.name, MAX(c2.population) AS pop FROM country  c, country c2 
WHERE c.continent = c2.continent GROUP BY continent

请帮助,我如何获得与上述子查询相同的结果。

提前致谢

1 个答案:

答案 0 :(得分:1)

您应该在子查询中获得MAX(population) GROUP BY continent,然后使用表本身JOIN获取; SELECT c1.continent, c1.NAME, c1.population FROM country c1 INNER JOIN ( SELECT continent, MAX(population) AS Maxp FROM country WHERE population > 0 GROUP BY continent ) AS c2 ON c1.population = c2.maxp AND c1.continent = c2.continent; 像这样:

{{1}}