我有一个名为Topics的表,我存储论坛主题:
topic_id
topic
description
created_by
date_created
status
另一个表帖子我存储主题的评论:
post_id
topic_id
user_id
content
date_created
然后第三列是评论表,我存储评论的回复:
comment_id
topic_id
post_id
user_id
reply_to_id
comment
date_created
如何使用MySQL语句计算每个主题的注释和回复总数?
编辑:到目前为止,我尝试了这个,但我没有得到正确的数字SELECT topics.topic_id,topics.topic, (COUNT(comments.topic_id)) AS count_comments
FROM topics
left join comments on topics.topic_id = comments.topic_id
left join posts on topics.topic_id = posts.topic_id
WHERE topics.created_by != 'Admin' and topics.status = '1'
GROUP by topics.topic_id
答案 0 :(得分:0)
SELECT tpc.topic ,
Count(cmt.comment) AS number of comments,
count(pst.content) AS number OF replies
FROM post pst,
comments cmt,
topics tpc
GROUP BY tpc.topic_id
答案 1 :(得分:0)
您可以尝试使用子查询来实现它:
SELECT `topics`.`topic_id`,
(SELECT COUNT(*) FROM `comments` WHERE (`comments`.`topic_id`=`topics`.`topic_id`)) `comments_count`,
(SELECT COUNT(*) FROM `posts` WHERE (`posts`.`topic_id`=`topics`.`topic_id`)) `posts_count`
FROM `topics`
WHERE (`topics`.`created_by` != 'Admin') AND (`topics`.`status` = '1')