SQL JOIN返回的记录多于预期

时间:2019-01-09 17:10:24

标签: sql join

我有桌子:

Country city population
------------------------
Israel  RG  100
Israel  TA  300
US  NY  900
US  SF  700

为了获得每个国家的最大人口,我正在运行以下查询:

select Country, max(population) as maxPopulation 
from A 
group by Country

我想获得完整的输出:

Country city population
-----------------------
Israel  TA  300
US  NY  900

要做到这一点,我需要加入整张桌子-如果我错了,请纠正我。

select A.Country, A.city, A.population 
from A 
right join
     (select Country,  max(population) as maxPopulation 
      from A 
      group by Country) temp on temp.Country = A.Country

这将返回所有4条记录...而不是2条记录...

2 个答案:

答案 0 :(得分:0)

您可以使用相关的子查询

select a.*
from a 
where population = (select max(a1.population) from a a1 where a1.Country = a.Country);

对于您的JOIN查询版本,您还需要一个其他条件,即. . . and temp.maxPopulation = A.Population以及为什么只需要inner join就可以在这里进行正确联接:

select a.*
from a inner join
       (select Country,  max(population) as maxPopulation 
        from a 
        group by Country
       ) temp 
       on temp.Country = a.Country and temp.maxPopulation = a.population; 

答案 1 :(得分:0)

我将使用标准的CTE:

with
x as (
  select country, max(population) as pop from A group by country
)
select A.*
from A
join x on x.country = A.country and x.pop = A.population

此查询的[希望?]副作用是,如果有多个城市具有相同的最大人口,则将全部显示。