如何在sql中正确使用count?

时间:2013-06-29 13:36:26

标签: sql group-by inner-join

我有两个表'匹配'和'论坛'我需要从匹配表中获取匹配信息,该表在论坛表中有评论,所以我使用以下查询:

SELECT distinct forum.match_static_id, matches.* 
from forum 
INNER JOIN matches 
  ON forum.match_static_id = matches.static_id 
WHERE forum.comments_yes_or_no = 1

如果在论坛表中有多个评论,我使用distinct来避免两次获得相同的匹配。

问题是我想用相同的查询得到每个匹配评论的计数是否可能?我用:

SELECT distinct forum.match_static_id, count(forum.comments), matches.* 
from forum 
INNER JOIN matches 
  ON forum.match_static_id = matches.static_i 
WHERE forum.comments_yes_or_no = 1

但它只给我一条记录(这是错误的)。问题是什么 ??我需要使用分组吗?如果是,那么在这个拥挤的查询中呢?

1 个答案:

答案 0 :(得分:0)

请试试这个:

SELECT forum.match_static_id, count(matches.id), matches.* 
from forum 
INNER JOIN matches 
  ON forum.match_static_id = matches.static_i
WHERE forum.comments_yes_or_no = 1
GROUP BY forum.id