加入2个表并得到巧合的总和

时间:2012-08-06 14:32:27

标签: sql group-by inner-join

注册用户的表格:

  • id_user
  • id_location
  • 名称

来自地点的表格:

  • id_location
  • 名称

我需要知道每个位置有多少用户。像这样:

  • 华盛顿:455
  • 佛罗里达州:185
  • 德克萨斯州:914

尝试了这种方法,但结果肯定是错误。

SELECT location.name,user.id_user FROM user
INNER JOIN location ON user.id_location = location.id_location
WHERE user.id_profile !=0 GROUP BY location.id_location ORDER BY location.name

2 个答案:

答案 0 :(得分:1)

SELECT location.id_location, location.name, COUNT(user.id_user) AS UserCount
FROM user 
INNER JOIN location ON user.id_location = location.id_location 
WHERE user.id_profile !=0 
GROUP BY location.id_location, location.name
ORDER BY location.name 

我已将id_location添加到查询中,以防您以某种方式拥有相同的位置名称,但位置ID不同。

答案 1 :(得分:1)

你真的很亲密,你只需要做COUNT

SELECT location.name, COUNT(user.id_user) UserCount 
FROM user
INNER JOIN location 
ON user.id_location = location.id_location
WHERE user.id_profile !=0 
GROUP BY location.name
ORDER BY location.name