关于SQL查询

时间:2012-01-17 11:52:24

标签: mysql sql database

我是SQL新手。目前,我正在学习编写复杂的查询。

我有三张桌子。 国家/地区 - 有国家/地区列表

-----------+-------------
 CountryId | CountryName
-----------+-------------
         1 | India
         2 | Srilanka
         3 | Pakistan
         4 | Bangladesh
         5 | Nepal
         6 | America
         7 | Japan
         8 | China
         9 | Russia
        10 | Canada
        11 | Australia
---------------------------------------

城市 - 国家/地区城市列表

--------+-------------+-----------
 CityId | CityName    | CountryId
--------+-------------+-----------
      1 | Chennai     |         1
      2 | Washington  |         6
      3 | Moscow      |         9
      4 | Tokyo       |         7
      5 | Beijing     |         8
      6 | Sydney      |        11
      7 | Bangalore   |         1
      8 | Nagercoil   |         1
      9 | AmericaCity |         6
     10 | Kathmandu   |         5
     11 | Dhaka       |         4
     12 | Lahore      |         3
--------------------------------------

机场 - 城市中的机场列表

 AirportId | AirportName | CityId
-----------+-------------+--------
         1 | Airport1    |      1
         2 | Airport2    |      4
         3 | Airport3    |      5
         4 | Airport4    |      1
         5 | Airport5    |      6
         6 | Airport6    |      3
         7 | Airport7    |      5
         8 | Airport8    |      7
         9 | Airport9    |      6
        10 | Airport10   |      3
        11 | Airport11   |     11
        12 | Airport12   |     10
        13 | Airport13   |     12
---------------------------------

问题:我想检索所有机场数量的国家/地区,例如

Output:
countryName Airports
India            3
Srilanka         0
......... etc.

5 个答案:

答案 0 :(得分:2)

SELECT a.AirportName, co.CountryName, COUNT(co.name) AS count
FROM Airports as a
LEFT JOIN City as c ON a.CityId = c.CityId
LEFT JOIN Country as co ON c.CountryId = co.CountryId
GROUP BY co.CountryId

答案 1 :(得分:1)

select 
  c.CountryName,
  SUM(
    select count(*) from Airport a
    inner join City city on city.CityId = a.CityId
    where city.CountryId = c.CountryId
    ) as Airports
from
  Country c

答案 2 :(得分:1)

SELECT CountryName, COUNT(CountryName) AS Airports

FROM Airports INNER JOIN City ON Airports.CityId = City.CityId
              INNER JOIN Country ON City.CountryId = Country.CountryId

GROUP BY CountryId

希望这对你有用

答案 3 :(得分:0)

SELECT
  Country.CountryName,
  count(*) AS Airports
FROM 
  Country
  INNER JOIN city ON Country.CountryId=city.CountryId
  INNER JOIN Airport ON city.CityId=Airport.CityId
GROUP BY Country.CountryId

答案 4 :(得分:0)

尝试:

SELECT
  Country.CountryId,
  Country.CountryName,
  count(AirportID) AS Airports
FROM 
  Country
  LEFT JOIN city ON Country.CountryId=city.CountryId
  LEFT JOIN Airport ON city.CityId=Airport.CityId
GROUP BY Country.CountryId