我如何使用选择查询的mysql计数?

时间:2015-07-25 14:56:57

标签: mysql select count

我有一个像这样的mysql选择查询:

select r.restaurant_id, r.restaurant_name, r.city_id, c.name
from restaurants r
inner join cities c on c.id = r.city_id;  

这是上述查询的结果:

+---------------+----------------------+---------+-------------+
| restaurant_id | restaurant_name      | city_id | name        |
+---------------+----------------------+---------+-------------+
|             7 | Somasiri Bake House  |       5 | Mumbai      |
|             8 | Indian    Bake House |       7 | Chennai     |
|             9 | KFC Rest             |       5 | Mumbai      |    
|            10 | Indian t             |       5 | Mumbai      |
+---------------+----------------------+---------+-------------+

现在我想显示所有可用的城市,其中包含一个城市的餐馆数量。

例如:孟买(3),金奈(1)等等

我尝试使用mysql COUN(),但它对我不起作用。

SELECT c.name, count(r.city_id) AS count
FROM cities c
INNER JOIN restaurants r ON c.id = r.city_id;

有谁可以告诉我这有什么问题?

希望有人可以帮助我。 谢谢。

3 个答案:

答案 0 :(得分:1)

这称为分组或聚合查询,您需要告诉它如何对元素进行分组。

添加

result["nodes"].flatten!.uniq!
result

最后,在你的最后一次分号之前。

答案 1 :(得分:1)

如果您不想要餐馆数据,请使用简单的小组:

select c.name, count(r.city_id) as available
from cities c
left join restaurants r on c.id = r.city_id
group by r.city_id

请参阅SQLFiddle

或者,如果您也想要餐馆数据,请先从城市中选择,然后再加入其他餐桌,以便仍然可以返回没有餐厅的城市。将左连接添加到子查询中,该子查询计算每个城市的频率:

select
  r.restaurant_id,
  r.restaurant_name,
  c.id,
  c.name,
  coalesce(available, 0) available
from cities c
left join restaurants r on c.id = r.city_id
left join (select city_id, count(*) available from restaurants group by 1) a
  on a.city_id = r.city_id

请参阅SQLFiddle

答案 2 :(得分:1)

SELECT c.name, COALESCE(count(r.city_id), 0) AS count
FROM cities c
LEFT JOIN restaurants r ON c.id = r.city_id
GROUP BY c.id