2017-06-18 77 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