高级SQL查询从ID引用结果中获取值

时间:2015-04-13 11:15:39

标签: mysql

我有两张表格,其中包含以下原理图

*City Table*

| ID | Name | CountryCode | District | Population
| 1  | York | GBP         | Yorkshire| 843844
| 2  | London ......

*Country Table*

| Code | Name | Continent | Region | Population | GNP | LocalName | Capital
| ABW  | Aruba| North Am  | Carrib | 843743     | x   | something | 834 (id)

我需要获得一个城市人口超过该城市首都人口的所有城市的清单。

我当前的SQL查询

SELECT City.ID, City.Name, Country.Name, City.District,               Country.Region, Country.Continent
FROM Country INNER JOIN City ON Country.Code = City.CountryCode 
WHERE (Country.Capital != City.ID) AND
(City.Population > (Country.Capital))
ORDER BY Continent;

它只是错过了最终过滤器(WHERE?),该过滤器声明人口必须大于该城市同一国家的首都城市。

有任何帮助吗?谢谢。

1 个答案:

答案 0 :(得分:0)

您需要两次加入City表:一个用于您要比较的实际城市,另一个用于首都:

SELECT City.ID, City.Name, Country.Name, City.District,           
    Country.Region, Country.Continent
FROM Country
INNER JOIN City ON Country.Code = City.CountryCode 
INNER JOIN City AS Capitals ON Country.Capital = Capitals.ID
WHERE (City.Population > Capitals.Population)
ORDER BY Continent;