分组并加入

Group by and Join

我在同一查询中使用 group by 和 join 时遇到问题。 (我在 MySQL 中使用世界数据库,只有两个 table。第一 - 国家,第二 - 城市)。我想获得每个大陆上最大的城市。这是我试过的

SELECT
    k.Continent,
    m.name,
    MAX(m.Population)
FROM
    city m
        JOIN
    country k ON m.CountryCode = k.Code
GROUP BY 1;

我在 population 和 continent 列中得到了很好的值,但城市名称是错误的。它不是人口最多的城市,而是table.

每个大洲的第一个城市

这是一个每组最大 n 的问题。您想要过滤而不是聚合。

您可以为此使用相关子查询:

select co.continent, ci.name, ci.population
from city ci
inner join country co where co.code = ci.countryCode
where ci.population = (
    select max(ci1.population)
    from city ci1
    inner join country co1 on co1.code = ci1.countryCode
    where co1.continent = co.continent
)

如果你有幸成为运行 MySQL 8.0,使用window函数更简单:

select *
from (
    select 
        co.continent, 
        ci.name, 
        ci.population, 
        rank() over(partition by co.continent order by ci.population desc) rn
    from city ci
    inner join country co where co.code = ci.countryCode
) t
where rn = 1

可能回答这个问题的最好方法是使用 window 函数,row_number():

SELECT Continent, name, Population
FROM (SELECT co.Continent, ci.name, ci.Population,
             ROW_NUMBER() OVER (PARTITION BY co.Continent ORDER BY ci.Population DESC) as seqnum
      FROM city ci JOIn
           country co
           ON ci.CountryCode = co.Code
     ) cc
WHERE seqnum = 1