2014-11-03 95 views
0

我有兩個表區域(名稱,編號),城市(地區編號,姓名,人口),我想返回人口最多的前5個城市以及該地區的名稱。這是我的查詢,但它只返回一個區域的5個城市(北在這種情況下),而不是所有地區:限制一列的結果

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

作爲一般規則,不要使用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名。

+0

它的工作,非常感謝你:) – Mera 2014-11-04 06:01:19

2

LIMIT是你的SQL關鍵字朋友,使用SELECT ... ORDER BY population LIMIT 5