我有以下表格结构:
所以每个论坛帖子都有一个家长,他也有一个家长(除了根帖子),等等。
我需要的是得到一个forumpost拥有的孩子的总数,包括他的孩子,孙子孙女等等。
现在我有一个简单的select,它返回直接的子项:
select count(*) as child_count
from forumposts
where parent_forum_post_id = $criteria.fid
我甚至不确定这是否可以通过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;
您可以通过修改条件来更改“起点”。
关于sql - 递归选择?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10191746/