2

id、parent_forum_post_idのテーブルフォーラム投稿があり、特定の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 に答える