创建一个从多个表中获取数据的查询
问题描述:
我正在尝试为我的类分配编写查询,但特别是我遇到了一个查询的问题。我遇到的问题涉及到每个国家的所有城市,并将它们从最多的城市显示到最少的城市。我想写的是查询的确切定义...创建一个从多个表中获取数据的查询
名单的国家按降序排列与该国开始与 在数据库中的城市数量最多,并与 国结束数据库中最少的城市数量。城市 具有相同数量的城市应按照字母顺序排序从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
答
名单的国家按降序排列与该国开始与 在数据库中的城市数量最多,并与 结束数据库中城市数量最少的国家。城市 具有相同数量的城市应按照字母顺序排序从A 到Z
- 为了找到
country with largest number of cities
或smallest number of cities
我们需要使用GROUP BY
和COUNT
其中按国家分组计数城市 - 对于
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
答
你可以尝试做一个查询为:
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
+0
好的,我会试试看,谢谢 – ryan 2014-10-12 04:41:01
我很欣赏这个解释,它真的帮了我很多! – ryan 2014-10-12 04:56:38
不客气。乐意效劳。 – Ram 2014-10-12 04:59:53
提供的查询在PostgreSQL中不起作用,因为没有'SORT BY'子句。 – vyegorov 2014-10-12 09:52:25