Sql 获取叶级递归选择

Sql 获取叶级递归选择,sql,postgresql,recursive-query,Sql,Postgresql,Recursive Query,我有一个id为parent\u forum\u post\u id的umposts表,对于给定的id=1221,我发现它是children count 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

我有一个id为parent\u forum\u post\u id的umposts表,对于给定的id=1221,我发现它是children count

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

    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      (count(*)-1) as child_count
from        all_posts
where       root_id=1221
group by    root_id;
我现在需要的恰恰相反:对于一个给定的id,找出它的级别,这取决于它的父母数量(它是父母,它是父母的父母,直到它在它的父母论坛帖子id列中找到null为止)。希望这是有意义的


感谢您的帮助。谢谢。

如果我理解正确,您需要给定特定节点id(根为级别1)的层次结构深度。这适用于postgresql:

with recursive all_posts (id, parentid, node_id) as (
    select  t1.id,
            t1.parent_forum_post_id as parentid,
            t1.id as node_id
    from    forumposts t1

    union all

    select  c1.id,
            c1.parent_forum_post_id as parentid,
            p.node_id
    from    forumposts c1
    join    all_posts p on p.parentid = c1.id
)
select      count(*) as level
from        all_posts
where       node_id=1221   
group by    node_id;
或者


此查询可以大大简化为:

WITH RECURSIVE p AS (
    SELECT parent_forum_post_id AS p_id
    FROM   forumposts
    WHERE  id = 1221   

    UNION ALL
    SELECT f.parent_forum_post_id
    FROM   p
    JOIN   forumposts f ON f.id = p.p_id
    )
SELECT count(*) AS level
FROM   posts;

也应该快得多。

嗨,谢谢你的帮助。但是,我得到的这个列anticendent.parent\u forum\u post\u id不存在。在postgresql中也是递归的。@Fofole-是的,我错了。这在Recrive部分的连接中。应该在
anticendent\u post\u id
上加入。更正。
SELECT
  *
FROM
  anticendent
WHERE
  post_id = 1221
  AND anticendent_post_id IS NULL
WITH RECURSIVE p AS (
    SELECT parent_forum_post_id AS p_id
    FROM   forumposts
    WHERE  id = 1221   

    UNION ALL
    SELECT f.parent_forum_post_id
    FROM   p
    JOIN   forumposts f ON f.id = p.p_id
    )
SELECT count(*) AS level
FROM   posts;