1

我有以下字段的评论表

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 

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

4

3 回答 3

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

于 2013-04-11T10:22:44.430 回答
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;
于 2013-04-11T10:33:19.617 回答
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_idGROUP BY c1.comment_id解决问题时,我正在分组。

于 2013-04-11T10:39:29.323 回答