I have the following table structure:
So each forum post has a parent,
Have you tried Recursive Queries Using Common Table Expressions
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
.
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
It's WITH RECURSIVE in Postgresql