Recursive select?

后端 未结 4 2154
深忆病人
深忆病人 2020-12-20 02:14

I have the following table structure:

\"enter

So each forum post has a parent,

相关标签:
4条回答
  • 2020-12-20 02:32

    Have you tried Recursive Queries Using Common Table Expressions

    0 讨论(0)
  • 2020-12-20 02:33

    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.

    0 讨论(0)
  • 2020-12-20 02:48
    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
    
    0 讨论(0)
  • 2020-12-20 02:49

    It's WITH RECURSIVE in Postgresql

    0 讨论(0)
提交回复
热议问题