gpt4 book ai didi

MySQL 错误 1242 : Subquery returns more than 1 row

转载 作者:行者123 更新时间:2023-11-29 12:14:35 25 4
gpt4 key购买 nike

我正在做一些 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 不高兴,因为我的子查询返回的行数比国家/地区名称选择器返回的行数多,但这正是我想要做的。我想要多行代表一个国家/地区值,一行代表每个满足人口高于平均人口搜索条件的城市。该作业还特别禁止我使用连接来解决这个问题。

最佳答案

加入应该可以做到这一点。您可以根据国家/地区代码加入城市,并过滤掉人口低于平均水平的城市

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)

关于MySQL 错误 1242 : Subquery returns more than 1 row,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com