gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:31:24 25 4
gpt4 key购买 nike

我正在使用 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)

最佳答案

这是 StackOverflow 上经常出现的“最大 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有相同的大陆和更多的人口。如果找不到(由外连接为 c2 的所有列返回 NULL 表示),则 c1 必须是该大陆上人口最多的国家.

请注意,如果排名第一的位置并列,则每个大陆可能会找到多个国家/地区。换句话说,可能有两个国家不存在人口更多的第三国。

关于sql - MySQL 世界数据库试图避免子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1813580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com