Sql 从2个表中获取数据并编写查询
我在php中遇到查询问题。我似乎没有得到我想要的结果。 我试图写的查询是 列出每个国家人口最多的城市和城市 那个城市的名字。按城市人口的降序排列结果 以下是我尝试过的代码,以及我尝试过的表格:Sql 从2个表中获取数据并编写查询,sql,postgresql,greatest-n-per-group,Sql,Postgresql,Greatest N Per Group,我在php中遇到查询问题。我似乎没有得到我想要的结果。 我试图写的查询是 列出每个国家人口最多的城市和城市 那个城市的名字。按城市人口的降序排列结果 以下是我尝试过的代码,以及我尝试过的表格: SELECT MAX(population) as population, name FROM what.city ORDER BY population DESC 以下是我正在使用的表格: Table "what.country" Column |
SELECT MAX(population) as population, name
FROM what.city
ORDER BY population 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 |
gnp_old | real |
local_name | character varying(45) | not null default ''::character varying
government_form | character varying(45) | not null default ''::character varying
目前接受的答案不正确。在Postgres中实现这一点的一个简单而快速的方法是使用
DISTINCT ON
:
SELECT co.name AS country_name, ci.city_name, population
FROM (
SELECT DISTINCT ON (country_code)
country_code, name AS city_name, population
FROM what.city
ORDER BY country_code, population DESC
) ci
JOIN what.coutry co USING (country_code);
详情:
SELECT co.name AS country_name, ci.city_name, population
FROM (
SELECT DISTINCT ON (country_code)
country_code, name AS city_name, population
FROM what.city
ORDER BY country_code, population DESC
) ci
JOIN what.coutry co USING (country_code);