简体   繁体   中英

SQL SELECT Cities

I have that homework to write a SQL query that:

  1. Selects countries where a total number of inhabitants (population) in all the cities is greater than 400
  2. Selects names of countries that have no buildings at all.

There is a tables definitions

http://imgur.com/hLZZ90F

I)

SELECT c1.Name
FROM Country c1
JOIN City c2 ON (c1.CountryID = c2.CountryID)
 WHERE NOT EXISTS 
       (SELECT *
          FROM City
         WHERE Population < 400)
;

Why isn't this correct ? I'm not getting any records.

There are several ways, this one works for the first case:

select *
from Country co
where 400 < all ( 
            select ci.Population 
            from City ci 
            where ci.CountryID = co.CountryID
            )

For the second case:

select *
from Country co
where 0 = (
    select COUNT(1)
    from City ci 
        JOIN Building B ON B.CityID = CI.CityID
    where ci.CountryID = co.CountryID
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM