2

我有以下表结构:

在此处输入图像描述

所以每个论坛帖子都有一个父母,他也有一个父母(除了根帖子)等。我需要的是获得一个论坛帖子的孩子总数,包括他的孩子的孩子,孙子的孩子等等。

现在我有一个简单的选择,它返回直接的孩子:

select count(*) as child_count 
from forumposts 
where parent_forum_post_id = $criteria.fid

我什至不确定这是否可以通过 sql 实现,但我是 SQL 的初学者,所以我想也许有人可以给出一些想法。

任何帮助表示赞赏。谢谢。

4

4 回答 4

6

这应该这样做:

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;

您可以通过修改条件来更改“起点” where t1.parent_forum_post_id is null

于 2012-04-17T13:25:26.193 回答
1

您是否尝试过使用公用表表达式的递归查询

于 2012-04-17T13:07:37.173 回答
0
WITH RecursiveCte AS
(
SELECT 1 AS LEVEL,
       H1.intUserId,
       H1.intReportsTo,
       H1.strUserName
FROM   mstUsers H1
WHERE  id = @intUserId
UNION ALL
SELECT RCTE.level + 1 AS LEVEL,
       H2.intUserId,
       H2.intReportsTo,
       H2.strUserName
FROM   mstUsers H2
       INNER JOIN RecursiveCte RCTE
            ON  H2.intReportsTo = RCTE.
)
SELECT intUserId,strUserName,LEVEL FROM RecursiveCte
于 2013-10-21T10:35:26.610 回答
0

在 Postgresql 中是WITH RECURSIVE

于 2012-04-17T13:09:45.100 回答