限制一列的结果

时间:2014-11-03 21:11:47

标签: mysql sql

我有两个表区域(名称,号码),城市(region_number,名称,人口),我想返回人口最多的前5个城市以及该地区的名称。这是我的查询,但它只返回一个区域的5个城市(在本例中为North)而不是所有区域:

SELECT region.name AS region_name, city.name AS city_name, city.population AS population
FROM region INNER JOIN (SELECT city.name, city.population, city.region_code
FROM county  LIMIT 5) AS city
ON region.code = city.region_code;

期望的输出:

     region_name |        city_name         | population 
------------+----------------------------+------------
 NORTH     | A                           |     226338
 NORTH     | B                           |      13656
 NORTH     | C                           |       9478
 NORTH     | D                           |       2464
 NORTH     | E                           |       2464
 WEST      | A                           |     226338
 WEST      | B                           |      13656
 WEST      | C                           |       9478
 WEST      | D                           |       2464
 WEST      | E                           |       2464

提前感谢您的帮助:)

2 个答案:

答案 0 :(得分:2)

LIMIT是您的SQL关键字朋友,请使用SELECT ... ORDER BY population LIMIT 5

答案 1 :(得分:2)

作为一般规则,请勿在没有limit的情况下使用order by。你有五个任意城市。

你要做的是在MySQL中有点痛苦。但是,以下内容应该有效:

SELECT r.name AS region_name, c.name AS city_name, c.population AS population
FROM region r INNER JOIN 
     county c
     ON r.code = c.region_code
WHERE 5 >= (SELECT count(*)
            FROM county c2
            WHERE c2.region_code = c.region_code and c2.population >= c.population
           )
ORDER BY region, population DESC;

where子句计算人口大于或大于给定城市的城市数量。返回的唯一城市是前5名。