2012-05-30 51 views
1

我有以下查詢:MySQL的:數列(含加盟)

Table zone: zone_id, country_id, city_id 

SELECT zone.zone_id, city_name 
FROM zone 
INNER JOIN city 
ON city.city_id = zone.city_id 
WHERE country_id = 3 

結果:

zone_id | city_id 
---------------------- 
17  | New York 
16  | Los Angeles 

及其他查詢:

Table zone , Table management relation: zone_id 

SELECT COUNT(user_id) 
FROM management 
WHERE zone_id = 17 

SELECT COUNT(user_id) 
FROM management 
WHERE zone_id = 16 

結果

first query: Count    second query: Count 
      -------       -------- 
      5        2 

我如何加入計數()的第一個查詢結果的每一行?這樣:

zone_id | city_id  | users 
-------------------------------- 
17  | New York  | 5 
16  | Los Angeles | 2 

我嘗試這樣做:

SELECT zone.zone_id, vNombre, COUNT(user_id) AS users 
FROM zone 
INNER JOIN city 
ON city.city_id = zone.city_id 
INNER JOIN management 
ON management.zone_id = zone.zone_id 
WHERE country_id = 3 
GROUP BY user_id 

,但我覺得這樣的:

zone_id | city_id  | users 
-------------------------------- 
17  | New York  | 5 
17  | New York  | 2 

回答

1
SELECT zone_id, city_name, COUNT(user_id) AS users 
FROM  zone 
    INNER JOIN city  USING (city_id) 
    LEFT JOIN management USING (zone_id) 
WHERE country_id = 3 
GROUP BY zone_id, city_name 
+0

感謝您的幫助 – csotelo