如何在MySQL中计算联接

时间:2019-01-16 14:12:37

标签: mysql

我有2张桌子

城市

Id | city_name 

愿望

Id | city_id | user_id

我想使用如下所示的MySQL查询创建表-

City Name | Number of Wanteds
Leeds     | 3
Manchester| 1
Halifax   | 0
Bradford  | 0

其中“通缉人数”是从“通缉”表中拉出的city_id总数。

我尝试过

select c.city_name, count(w.city_id) from cities c inner join wanteds w on c.id = w.city_id 

但是它只返回第一个城市的总数。

1 个答案:

答案 0 :(得分:1)

您需要添加group by子句

  select c.city_name, count(w.city_id) 
  from cities c inner join wanteds w on c.id = w.city_id
  group by c.city_name