在 SQL 中嵌套查询

问题描述 投票:0回答:4

我的查询的目标是返回国家名称及其国家元首,如果该国家元首的名字以 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 子句等中。我没有得到嵌套查询。我只是收到错误,例如“子查询返回不止一行”之类的。如果有人可以帮助我如何订购,并解释为什么需要以某种方式订购,那就太好了。

sql nested
4个回答
17
投票

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

SELECT o.name AS country, o.headofstate 
FROM   country o
WHERE  o.headofstate like 'A%'
AND   (  -- guaranteed to return a single value
    SELECT i.population
    FROM   city i
    WHERE  i.id = o.capital
    ) > 100000;

“嵌套查询”是该任务的一个奇怪的要求。 A

JOIN
更简单、更高效:

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

9
投票

您需要

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%'

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 的观点:为什么要使用嵌套查询?


2
投票

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

select scountry, headofstate from data 
where data.scountry like 'a%'and ttlppl>=100000
© www.soinside.com 2019 - 2024. All rights reserved.