我正在做一些SQL的家庭作业,我在这个问题上走到了尽头,我希望有人可以指出我在这里做错了什么。
SELECT Name,
(SELECT Name
FROM City
WHERE City.CountryCode = Country.Code) AS 'city',
(SELECT Population
FROM City
WHERE City.CountryCode = Country.Code) AS 'city_population'
FROM Country
WHERE Region IN ('Western Europe')
HAVING city_population > (SUM(Population) / COUNT(city))
ORDER BY Name, city;
我在这里要做的是从全球统计数据库中检索一个城市列表(来自城市表)与该表中的国家匹配,其中该国家位于西欧地区该城市的人口大于该国的城市平均人口,按国家和城市名称排序。 CountryCode和Code是表格的关键。
谁能告诉我哪里出错了?我猜MySQL是不开心的,因为我的子查询返回的行数多于国家/地区名称的选择器,但这正是我想要做的。我想要一个国家/地区值的多行,每个城市的一行符合搜索条件的人口数超过平均水平。该任务还特别禁止我使用连接来解决这个问题。
答案 0 :(得分:1)
联接应该这样做。您可以在国家/地区代码上加入城市,并过滤掉人口低于平均水平的城市
GROUP_CONCAT
<强>附加:强> 由于您不允许使用连接,因此您可以通过几种方式解决它。
1)您可以稍微更改一下您的查询,但不会为每个城市返回行。相反,它会将城市列表作为单个字段返回。这只是对您的查询的轻微修改。请注意SUM
函数,它的作用类似于ORDER BY
,它只会对值进行汇总而不是对它们求和。另请注意子选择中添加的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;
子句,这样您就可以确保第n个人口匹配第n个城市名称。
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)
2)您可以通过查询稍微改变一下。删除Country上的连接,而是在过滤器和select中使用一些子选择。只有在您需要国家名称时才需要后者。如果国家/地区代码足够,您可以从City中选择。
{{1}}
答案 1 :(得分:0)
语句的select部分中的子查询只需要从查询返回一个值。请记住,将select语句中的值分开的逗号表示列,每列需要一个值。为了获取子查询中返回的值列表(就好像它是另一个表)并在外部查询中使用它,您必须将子查询放在Query的from
部分中。注意:这可能不是您的结果的正确代码。我刚刚解决了MySQL错误1242的问题。
SELECT Name
FROM Country, (SELECT Name
FROM City
WHERE City.CountryCode = Country.Code) AS 'city',
(SELECT Population
FROM City
WHERE City.CountryCode = Country.Code) AS 'city_population'
WHERE Region IN ('Western Europe')
HAVING city_population > (SUM(Population) / COUNT(city))
ORDER BY Name, city;