mysql查询从表中获取计数

时间:2014-11-26 13:15:14

标签: mysql

我有3张这样的表:

Areas 
id      city_id         area
1       1               mayfield
2       2               cleveland

neighbourhood
id      neighbourhood   area_id
101     cayahoga        1
102     milan           1
103     downtown        2

Salons
id      neighbourhood_id
3       101
4       101
5       102

我正在努力计算所有领域的所有沙龙。

像地区的沙龙一样(mayfield = 2,克利夫兰= 1)

是否可以在1个查询中执行此操作?

2 个答案:

答案 0 :(得分:1)

select area,count(s.id) as salon_count FROM
Areas a
INNER JOIN neighbourhood n
ON a.id = n.area_id
INNER JOIN
Salons s on s.neigbourhood_id = n.id
GROUP BY area

答案 1 :(得分:1)

SELECT areas.area,COUNT(Salons.id)
FROM areas
LEFT JOIN neighbourhood ON neighbourhood.area_id = areas.id
LEFT JOIN Salons ON Salons.neighbourhood_id = neighbourhood.id
GROUP BY areas.id