创建从多个表中获取数据的查询

时间:2014-10-12 04:22:39

标签: sql postgresql

我正在尝试为我的类分配编写查询,但我特别遇到一个查询问题。我遇到问题的查询统计每个国家/地区的所有城市,并将其显示在最大数量的城市和最小数量的城市中。我想写的查询的确切定义是......

  

从国家/地区开始按降序列出国家/地区   数据库中最多的城市,以及以   数据库中城市数量最少的国家/地区。城市   具有相同数量的城市应按字母顺序排序   从A到Z。

我现在要发布我为此查询尝试的代码以及我用来完成它的表。

SELECT country.name 
FROM what.country as name 
INNER JOIN what.city as city ON name.country_code = city.country_code 
SORT BY name DESC

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

             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
 life_expectancy | real                  | 
 gnp             | real                  | 

             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

2 个答案:

答案 0 :(得分:1)

您可以尝试执行以下搜索:

SELECT A.name AS name, IFNULL(B.cities, 0) AS cities
FROM what.country AS A
LEFT JOIN (SELECT country_code, count(id) AS cities FROM what.city GROUP BY country_code) AS B
ON A.country_code = B.country_code
ORDER BY cities DESC, name ASC

答案 1 :(得分:0)

  

从国家/地区开始按降序列出国家/地区   数据库中最多的城市,以及以   数据库中城市数量最少的国家/地区。城市   具有相同数量的城市应按字母顺序排序   从A到Z。

  • 要查找country with largest number of citiessmallest number of cities,我们需要使用GROUP BYCOUNT按国家/地区进行分组和计算城市
  • descending order使用city_count DESC使用same number of cities should be sorted alphabetically使用country_name

代码

SELECT country.name AS country_name, COUNT(city.id) AS city_count
FROM what.country as name 
INNER JOIN what.city as city ON name.country_code = city.country_code
GROUP BY  country.name
ORDER BY city_count DESC, country_name