2

I have the following table structure:

enter image description here

So each forum post has a parent, who also has a parent(except the root posts), etc. What I need is to get the total number of children a forumpost has, including his children's children, grandchildren's children and so on.

For now I have a simple select that returns the immediate children:

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

I'm not even sure this is doable via sql, but I'm a begginer in SQL so I thought maybe someone can give some ideas.

Any help is appreciated. Thanks.

Community
  • 1
  • 1
Fofole
  • 3,398
  • 8
  • 38
  • 59
  • This thread may help: http://stackoverflow.com/questions/1323245/sql-recursion-without-recursion – Logan Serman Apr 17 '12 at 13:03
  • The next time please post the sample data as `INSERT` statements. Or at least as text. That way it's easier for those answering to setup a test-table with data. –  Apr 17 '12 at 13:26

4 Answers4

6

This should do it:

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;

You can change the "starting" point by modifying the condition where t1.parent_forum_post_id is null.

1

Have you tried Recursive Queries Using Common Table Expressions

Marshal
  • 6,551
  • 13
  • 55
  • 91
0

It's WITH RECURSIVE in Postgresql

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
Surendra
  • 237
  • 3
  • 6
  • 19