PSQL中的查询从2个不同的表中获取信息

时间:2014-10-11 18:31:33

标签: sql postgresql

我正在尝试从不同的表中编写查询,但有一个查询我遇到了问题。我们使用PSQL来进行这些查询。我想要执行的查询是:

  

对于数据库中至少有一百个城市的每个国家/地区,请列出其包含的城市总数。按照城市数量的升序排列结果。

我知道我将不得不使用计数功能来获取城市的数量,但我对如何列出城市总数感到困惑。这是我尝试过的代码:

SELECT country.name AS name, COUNT(city.name) AS num_cities 
FROM what.country 
WHERE  (num_cities > 100) 
ORDER BY num_cities ASC

以下是我正在使用的两个表:

              Table "what.country"
     Column      |         Type          |               Modifiers              
-----------------+-----------------------+--------------------------------------
 country_code    | character(3)          | not null default ''::bpchar
 name            | character varying(52) | not null default ''::character varying
 continent       | continent             | not null
 region          | character varying(26) | not null default ''::character varying
 surface_area    | real                  | not null default 0::real
 indep_year      | smallint              | 
 population      | integer               | not null default 0


                 Table "what.city"
    Column    |         Type          |                     Modifiers                    
--------------+-----------------------+-----------------------------------------
 id           | integer               | not null default nextval('city_id_seq'::regclass)
 name         | character varying(35) | not null default ''::character varying
 country_code | character(3)          | not null default ''::bpchar
 district     | character varying(20) | not null default ''::character varying
 population   | integer               | not null default 0

1 个答案:

答案 0 :(得分:1)

您需要使用GROUP BY和HAVING来获得至少拥有100个城市的国家/地区

    SELECT country.name AS name   
    COUNT(city.name) AS   
    num_cities 
    FROM country 
    JOIN city 
    ON country.country_code =
    city.country_code
    GROUP BY country.nam
    HAVING COUNT(city.name) >=100
    ORDER by COUNT(city.name) ASC