我有以下表结构:

所以每个论坛帖子都有一个父母,父母也有父母(根帖除外)等等.我需要的是获得一个孩子的总数,包括他孩子的孩子,孙子女的孩子等等.
现在我有一个简单的选择返回直接的孩子:
select count(*) as child_count
from forumposts
where parent_forum_post_id = $criteria.fid
Run Code Online (Sandbox Code Playgroud)
我甚至不确定这是否可以通过sql,但我是SQL的初学者,所以我想也许有人可以给出一些想法.
任何帮助表示赞赏.谢谢.
这应该这样做:
with recursive all_posts (id, parentid, root_id) as
(
select t1.id,
t1.parent_forum_post_id as parentid,
t1.id as root_id
from forumposts t1
where t1.parent_forum_post_id is null
union all
select c1.id,
c1.parent_forum_post_id as parentid,
p.root_id
from forumposts c1
join all_posts p on p.id = c1.parent_forum_post_id
)
select root_id, count(*)
from all_posts
order by root_id;
Run Code Online (Sandbox Code Playgroud)
您可以通过修改条件来更改"起始"点where t1.parent_forum_post_id is null.