[英]Getting total number of comments of post in mysql using count() always returns 1 even if no comment is present for particular post
I have two tables in my database 我的数据库中有两个表
1.Stories (id,title,content) 1.故事(id,title,content)
2.Comments (id,story_id,comment) here story_id
is forigen key refers id
in stories
table. 2.Comments(id,story_id,comment)这里的story_id
是stories
表中的id
键。
In order to get the comments of a particular post i am using this query 为了获取特定帖子的评论,我正在使用此查询
SELECT stories.*,COUNT(stories.id) as totalcomment
FROM stories LEFT JOIN comments ON stories.id=comments.story_id GROUP BY stories.id
Problem is i will get totalcomment
value is 1 even if no comments for a particular post it should be 0 ,but i will get count(storie.id)
result as 1 问题是即使对某个特定帖子没有评论,我也将获得totalcomment
值为1,但我将count(storie.id)
结果设为1
You need to count Comments.story_id
and also group by Comments.story_id
. 您需要计算Comments.story_id
并按Comments.story_id
分组。
You have more than one comments for each stories, so your result goes always 1 when you group by that stories.id
, you need to count the Comments.story_id
so that for each stories it counts all the comments at once and also make a group by of it. 每个故事有多个评论,因此按该stories.id
分组时,结果始终为1。您需要计算Comments.story_id
以便对于每个故事,它可以一次计算所有评论并组成一个小组通过它。
SQL 的SQL
SELECT stories.*,COUNT(Comments.story_id) as totalcomment
FROM stories LEFT JOIN comments ON stories.id=comments.story_id GROUP BY stories.id, Comments.story_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.