Mysql 分组并加入
在同一查询中使用group by和join时出现问题。(我在MySQL中使用WorldDB,只有两个表。第一个是国家,第二个是城市)。我想得到每个大陆上最大的城市。这是我试过的Mysql 分组并加入,mysql,sql,join,select,greatest-n-per-group,Mysql,Sql,Join,Select,Greatest N Per Group,在同一查询中使用group by和join时出现问题。(我在MySQL中使用WorldDB,只有两个表。第一个是国家,第二个是城市)。我想得到每个大陆上最大的城市。这是我试过的 SELECT k.Continent, m.name, MAX(m.Population) FROM city m JOIN country k ON m.CountryCode = k.Code GROUP BY 1; 我在人口和大陆栏中得到了很好的值,但城市名
SELECT
k.Continent,
m.name,
MAX(m.Population)
FROM
city m
JOIN
country k ON m.CountryCode = k.Code
GROUP BY 1;
我在人口和大陆栏中得到了很好的值,但城市名称是错误的。它不是人口最多的城市,而是表中各大洲的第一个城市。这是一个最大的群体问题。您希望筛选而不是聚合 您可以为此使用相关子查询:
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
回答这个问题的最好方法可能是使用窗口函数,
row\u number()
:
向我们展示一些示例表数据和预期结果-作为格式化文本,而不是图像。和阅读。你通常按照与你选择相同的列进行分组,除了那些设置函数的参数。你使用的是哪个MySQL版本?MySQL版本8.0太好了,看看GMB的答案。
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