简体   繁体   English

如何在SQL中正确使用计数?

[英]How to use count correctly in sql?

I have tow tables 'matches' and 'forum' I need to get match information from the matches table which has comments in the forum table so I use the following query: 我有两个表“ matches”和“ forum”,我需要从matches表中获取匹配信息,该表在forums表中有注释,因此我使用以下查询:

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

I use distinct to avoid getting the same match twice if it has more than one comment in the forum table. 如果论坛表中有多个评论,我会使用distinct来避免两次相同的比赛。

The problem is I want to get the count of each match comments with the same query is it possible? 问题是我想使用相同的查询获取每个匹配评论的数量吗? I use : 我用 :

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

but it give me just one record (which is wrong). 但它只给我一个记录(这是错误的)。 What is the problem ?? 问题是什么 ?? does I need to use group by ? 我需要使用分组依据吗? and if yes where to but it in this crowded query? 如果是的话,但是在这个拥挤的查询中呢?

Please try this: 请尝试以下方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM