2

私は次のテーブル構造を持っています:

ここに画像の説明を入力してください

したがって、各フォーラム投稿には親があり、その親にも親があります(ルート投稿を除く)。必要なのは、フォーラム投稿の子の総数(子の子、孫の子など)を取得することです。

今のところ、直接の子を返す単純な選択があります。

select count(*) as child_count 
from forumposts 
where parent_forum_post_id = $criteria.fid

これがSQLで実行できるかどうかさえわかりませんが、私はSQLの初心者なので、誰かがアイデアを提供できるのではないかと思いました。

どんな助けでも大歓迎です。ありがとう。

4

4 に答える 4

6

これはそれを行う必要があります:

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;

条件を変更することにより、「開始」ポイントを変更できますwhere t1.parent_forum_post_id is null

于 2012-04-17T13:25:26.193 に答える
1

一般的なテーブル式を使用した再帰クエリを試しましたか

于 2012-04-17T13:07:37.173 に答える
0

Postgresqlでは再帰的です

于 2012-04-17T13:09:45.100 に答える
0
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
于 2013-10-21T10:35:26.610 に答える