2017-06-18 80 views
0

我需要组织帖子到简单的论坛结构。每篇文章都有标题,说明,post_id和parent_post_id。 parent_post_id = -1的帖子是根顶级论坛。SQL查询计算所有儿童论坛主题和帖子

Forum 1 
    - Topic 1 
    - Post 1 
    - Post 2 
Forum 2 
    - Topic 2 
    - Post 3 
    - Post 4 

如何统计论坛1,论坛2等所有嵌套帖子?

到目前为止,我有以下查询

select forum.title, count(comment.post_id) as count from post as forum 
    left outer join post as topic on topic.parent_post_id = forum.post_id 
    left outer join post as comment on comment.parent_post_id = topic.post_id 
    where forum.parent_post_id = -1 
    group by forum.title 

但它返回错误的结果。

+0

删除'GROUP BY'并选择您想要的列。您的查询与您指定的结果没有多大关系。如果您将所需结果指定为具有固定列和行的结果集,将会有所帮助。 –

+0

然后Mysql说:“SQLSTATE [42000]:语法错误或访问冲突...与sql_mode = only_full_group_by不兼容” – ymakux

+0

可能是错误的结果,因为您正在使用**左连接** – Frank

回答

1

试试这个

select forum.title, count(comment.post_id) as count from (select * from post where parent_post_id = -1) as forum 
    left outer join post as topic on topic.parent_post_id = forum.post_id 
    left outer join post as comment on comment.parent_post_id = topic.post_id 
    group by forum.title