【问题标题】:Group by and Join分组和加入
【发布时间】:2020-08-04 01:35:15
【问题描述】:

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

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

我在人口和大陆列中获得了不错的值,但城市名称错误。它不是人口最多的城市,而是每个大陆上排名第一的城市。

【问题讨论】:

  • 向我们展示一些示例表数据和预期结果 - 作为格式化文本,而不是图像。并阅读minimal reproducible example
  • 您通常 GROUP BY 与您 SELECT 相同的列,除了那些是设置函数的参数的列。
  • 您使用的是哪个 MySQL 版本?
  • MySQL 8.0 版
  • 很好,看看 GMB 的回答。

标签: mysql sql join select greatest-n-per-group


【解决方案1】:

这是每组最大 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,使用窗口函数会更简单:

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

【讨论】:

    【解决方案2】:

    可能回答这个问题的最好方法是使用窗口函数,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
    

    【讨论】:

      猜你喜欢
      • 2011-09-17
      • 2021-12-31
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多