Sql 从2个表中获取数据并编写查询

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 |

我在php中遇到查询问题。我似乎没有得到我想要的结果。 我试图写的查询是

列出每个国家人口最多的城市和城市 那个城市的名字。按城市人口的降序排列结果

以下是我尝试过的代码,以及我尝试过的表格:

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);
详情:


Ur缺少分组依据。选择MAX(population)作为population,name FROM what.city group by name ORDER by MAX(population)desc如果您在“似乎没有获得我想要的输出”中展开,这会很有帮助。i、 e.如果你得到了一个错误,请告诉我们一个错误,或者描述你得到的与你期望的相比。@jimmy,你能接受我的答案吗,Erwin的正确答案与你的答案匹配。要删除我的答案,我只是在帮他查询,但你的答案正在帮助OP得到他们想要的want@radar:您不能删除已接受的答案。我在上面做了标记以引起主持人的注意。他们会帮忙的。
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);