1

我有以下查询:

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

如何将 count() 加入到第一个查询结果的每一行?,以这种方式:

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
4

1 回答 1

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
于 2012-05-30T22:15:16.750 回答