2

我有一个带有 id,parent_forum_post_id 的表 forumposts,对于给定的 id=1221,我发现它的孩子数。

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,找出它的级别,这取决于他的父母数量(它是父母,它是父母的父母,直到它在它的 parent_forum_post_id 列中找到 null)。希望这是有道理的。

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

4

3 回答 3

3

此查询可以在很大程度上简化为:

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;

也应该快得多。

于 2012-05-01T00:17:46.510 回答
2
WITH recursive
  anticendent
AS
(
  SELECT
    id                       AS post_id,
    parent_forum_post_id     AS anticendent_post_id,
    1                        AS distance
  FROM
    forumposts

  UNION ALL

  SELECT
    anticendent.post_id,
    forumposts.parent_forum_post_id,
    distance + 1
  FROM
    anticendent
  INNER JOIN
    forumposts
      ON forumposts.id = anticendent.anticendent_post_id
)

SELECT
  post_id,
  MAX(distance)  AS level
FROM
  anticendent
GROUP BY
  post_id
WHERE
  post_id = 1221

或者...

SELECT
  *
FROM
  anticendent
WHERE
  post_id = 1221
  AND anticendent_post_id IS NULL
于 2012-04-30T13:39:29.223 回答
1

如果我理解正确,您希望特定节点的层次结构深度给定其 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;
于 2012-04-30T13:37:50.410 回答