SQL Query根据列条目获取有限数量的结果

时间:2012-08-23 12:35:53

标签: mysql sql database population

我现在正在努力解决SQL问题。

我有一个包含行ID,名称,国家,人口的表城市。

ID  |     name     |  country  | population 
1   | Shanghai     | CN        | 14608512
2   | Buenos Aires | AR        | 13076300
3   | Mumbai       | IN        | 12691836
4   | Karachi      | PK        | 11624219
5   | Beijing      | CN        |  7480601
6   | Wuhan        | CN        |  4184206
7   | Berlin       | DE        |  3426354
8   | Puyang       | CN        |  3590000

该数据库包含来自所有人口超过15000的城市的全球数据。现在我正在尝试按人口计算获得世界上50个最大的城市。

SELECT * FROM cities ORDER BY population DESC LIMIT 0,50

我现在的问题是我在中国有12个城市,在印度有4个城市等。但我需要按国家限制我的结果,因此每个国家只返回2个城市。

以上示例的结果:

ID  |     name     |  country  | population 
1   | Shanghai     | CN        | 14608512
2   | Buenos Aires | AR        | 13076300
3   | Mumbai       | IN        | 12691836
4   | Karachi      | PK        | 11624219
5   | Beijing      | CN        |  7480601
7   | Berlin       | DE        |  3426354

但就像我说的那样,我正在努力使用正确的sql查询来进行这种操作。我尝试了GROUP BY ... HAVING和各种子选择,但似乎都没有返回正确的结果集。

1 个答案:

答案 0 :(得分:1)

试试这个:

select * from
    (select t.* from t_population t
    join
        (select  country,MAX(population) as population
         from    t_population
         group by country)a
    on  t.country=a.country
    and t.population=a.population
union all
    select t.* from t_population t
    join
        (select country,MAX(population) as population
         from   t_population t1
         where  population <> (select MAX(population) 
         from  t_population t2 where t1.country=t2.country)
         group  by country)b
    on t.country=b.country
    and t.population=b.population)c
order by  population desc


SQL Fiddle Demo