12

我的查询的目标是返回国家名称及其国家元首,如果它的国家元首的名称以 A 开头,并且该国家的首都有超过 100,000 人使用嵌套查询。

这是我的查询:

SELECT country.name as country, 
       (SELECT country.headofstate 
        from country 
        where country.headofstate like 'A%')      
from country, city 
where city.population > 100000;

我试过反转它,将它放在 where 子句等中。我没有得到嵌套查询。我只是收到错误,例如“子查询返回多行”等。如果有人可以帮助我如何订购它,并解释为什么它需要以某种方式,那就太好了。

4

4 回答 4

16

如果必须“嵌套”,这将是完成工作的一种方法:

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000

不过, AJOIN会比相关子查询更有效。有没有可能,给你这个任务的人自己没有跟上进度?

于 2012-09-17T21:46:22.910 回答
8

您需要join这两个表,然后在where子句中过滤结果:

SELECT country.name as country, country.headofstate 
from country
inner join city on city.id = country.capital
where city.population > 100000
and country.headofstate like 'A%'
于 2012-09-17T21:30:38.133 回答
2

在我看来,嵌套查询的唯一位置是在 WHERE 子句中,例如

SELECT country.name, country.headofstate
FROM country 
WHERE country.headofstate LIKE 'A%' AND 
country.id in (SELECT country_id FROM city WHERE population > 100000)

除此之外,我必须同意 Adrian 的观点:为什么要使用嵌套查询?

于 2012-09-17T21:46:45.333 回答
1

下面的查询应该可以帮助您实现您想要的。

select scountry, headofstate from data 
where data.scountry like 'a%'and ttlppl>=100000
于 2014-06-25T12:00:47.940 回答