连接应该做到这一点。您可以根据国家代码加入城市,并过滤掉人口低于平均水平的城市
select
co.Name as CountryName,
ci.Name as CityName,
ci.Population as CityPopulation
from
Country co
inner join City ci
on ci.CountryCode = co.CountryCode
where
co.Region in ('Western Europe')
and ci.Population >
(select sum(ca.Population) / count(*) from City ca
where ca.CountryCode = co.CountryCode)
补充:
由于不允许使用联接,因此可以通过多种方式解决。
1) 您可以稍微更改您的查询,但它不会返回每个城市的行。相反,它将城市列表作为单个字段返回。这只是对您的查询的轻微修改。请注意GROUP_CONCAT 函数,它的工作方式类似于SUM,只是它连接值而不是求和它们。还要注意子选择中添加的ORDER BY 子句,因此您可以确保第 n 个人口与第 n 个城市名称匹配。
SELECT Name,
(SELECT GROUP_CONCAT(Name)
FROM City
WHERE City.CountryCode = Country.Code
ORDER BY City.Name) AS 'city',
(SELECT GROUP_CONCAT(Population)
FROM City
WHERE City.CountryCode = Country.Code
ORDER BY City.Name) AS 'city_population'
FROM Country
WHERE Region IN ('Western Europe')
HAVING city_population > (SUM(Population) / COUNT(city))
ORDER BY Name, city;
2) 您可以通过查询稍作更改。删除 Country 上的连接,而是在过滤器和选择中使用一些子选择。仅当您需要国家名称时才需要后者。如果国家代码足够,您可以从城市中选择。
select
(select County.Name
from Country
where County.CountyCode = ci.CountryCode) as CountryName,
ci.CountryCode,
ci.Name as CityName,
ci.Population
from
City ci
where
-- Select only cities in these countries.
ci.CountryCode in
( select co.CountryCode
from Country co
where co.Region in ('Western Europe'))
-- Select only cities of above avarage population.
-- This is the same subselect that existed in the join before,
-- except it matches on CountryCode of the other 'instance' of
-- of the City table. Note, you will _need_ to use aliases (ca/ci)
-- here to make it work.
and ci.Population >
( select sum(ca.Population) / count(*)
from City ca
where ca.CountryCode = ci.CountryCode)