如何计算同一个表中的子注释

时间:2013-04-11 10:02:15

标签: mysql sql

我的评论表包含以下字段

comment_id                      
parent_id                       
thread_id 
title   
body                
date_comment                            
user_name

我需要检索所有父注释(在parent_id中具有NULL值)并根据每个父注释计算子注释 我尝试过以下查询

SELECT c1. * , COUNT( c2.parent_id ) 
FROM comments c1
LEFT JOIN comments c2 ON c2.parent_id = c1.comment_id
WHERE c1.parent_id IS NULL 
AND c1.thread_id =122
GROUP BY c2.parent_id
ORDER BY c1.date_comment ASC 

但是此查询只计算前三个父评论的子评论。 请分析查询并建议我解决方案。

3 个答案:

答案 0 :(得分:0)

我认为问题在于您正在对已连接类的parent_id进行分组。这具有您描述的效果,其中忽略没有子项的注释。我认为这样可行:

SELECT c1.*, COUNT( c2.parent_id ) AS childcount
FROM comments c1
LEFT JOIN comments c2 ON c2.parent_id = c1.comment_id
WHERE c1.thread_id =122
GROUP BY c1.comment_id
ORDER BY c1.date_comment ASC 

您可以在此处查看我的解决方案作为SQLFiddle:http://www.sqlfiddle.com/#!2/a8997/1

答案 1 :(得分:0)

由于缺少样本数据而未经测试的查询,但我希望它有效。

生成一个表,其中只包含按parent_id分组的计数并将其与原始表连接:

SELECT c1.*, c2.n
FROM comments c1
LEFT JOIN ( SELECT COUNT(*) as n
            FROM comments
            WHERE parent_id IS NOT NULL
            GROUP BY parent_id ) c2
WHERE c1.parent_id IS NULL
ORDER BY c1.date_comment ASC;

答案 2 :(得分:0)

感谢上帝。我得到了解决方案

SELECT c1. * , COUNT( c2.parent_id ) 
FROM comments c1
LEFT JOIN comments c2 ON c2.parent_id = c1.comment_id
WHERE c1.parent_id IS NULL 
AND c1.thread_id =122
GROUP BY c1.comment_id
ORDER BY c1.date_comment ASC

正如@Erik Schierboom所说,我在按c2.parent_id进行分组。当我用GROUP BY c2.parent_id替换GROUP BY c1.comment_id时,问题解决了。