SQL 处理子查询错误代码:1111

SQL dealing with subqueries Error Code: 1111

我正在尝试学习一些 SQL,所以我一直在摆弄示例世界架构。对于此查询,目标是针对每个大陆检索预期寿命高于该大陆平均寿命的国家/地区的首都。

下面的代码是我的尝试,但我在 where 语句中收到 1111 错误。任何帮助将不胜感激!

SELECT continent AS Continent,
       city.name AS Capital
FROM city,
     country c1
WHERE c1.capital = city.id
  AND avg(LifeExpectancy) <
    (SELECT avg(LifeExpectancy)
     FROM country c2
     WHERE c2.continent = c1.continent );

根据你的问题陈述,你不需要首都的平均预期寿命,只需要与首都对应的国家的预期寿命大于该大陆的平均预期寿命。因此,我在下面的查询中进行了这些调整。

让我知道这有效。

SELECT continent AS Continent,
       city.name AS Capital
FROM city,
     country c1
WHERE c1.capital = city.id
  AND c1.LifeExpectancy >
    (SELECT avg(LifeExpectancy)
     FROM country c2
     WHERE c2.continent = c1.continent );

您必须正确地将表 countrycity 连接到一个查询,该查询 returns 每个大陆的平均值 lifeexpectancy

select co.code, ci.name
from country co
inner join city ci on ci.id = co.capital
inner join (
  select continent, avg(lifeexpectancy) avg_lifeexpectancy
  from country
  group by continent
) t on t.continent = co.continent and t.avg_lifeexpectancy < co.lifeexpectancy