搜索
您的当前位置:首页正文

统计评论个数(mysql)

来源:知库网

需求场景是blog的文章列表,需要展示评论的个数。

被评论的主题信息表auc_owner_top

image.png

评论表chat,通过topic跟评论实体关联

image.png

我这里chat不止关联一个评论主题,所以没用topic直接关联主题表的id(因为多个实体的id是会重复的),这两张表是通过评论表的topic关联的主表的owner,关联的逻辑是:

"ownertop_"+auc_owner_top.owner = chat.topic

所以sql如下

select t.id,t.owner,t.count,t.update_time,count(c.id) as comment_counts 
from auc_owner_top t
left join chat c on concat('ownertop_',t.`owner`)=c.topic
group by t.owner
order by t.id

逻辑是:
1、首先以被评论的主体为主表,左连接评论表,避免0评论不会被忽略。

image.png

然后group by owner,count的根据chat.id,这样0评论的,comment_counts就是0

Top