PostgreSQL 如何在递归查询中计算记录数

Dan*_*pka 2 postgresql recursion

我想计算节点的所有后代

with recursive t as (
  select a.id, 0 cntr from a 
   where parent_id = 12 union all
  select a.id, cntr + 1 from t 
  join a on a.parent_id = t.id 
   where cntr <= 100
)

select * from t
Run Code Online (Sandbox Code Playgroud)

但这个例子得到了深度计数。我想获得所有后代的不同级别,并限制它。结果是这样的:

12, 0
13, 1
17, 2
...
232, 100
Run Code Online (Sandbox Code Playgroud)

表非常大,选择 * 并计算它 - 不是一个选项 我该怎么做?

JNe*_*ill 5

你很接近。您需要保留 id 作为子级,以便在递归术语中加入父级(您不必最终选择它,但它需要在您的联接中出现)。当您选择时,您想要每个 的记录计数id,您的计数器实际上更像是 a depth,但如果您的层次结构不是线性的(就像它分支一样),那么就depth不能完全得到您想要的。

with recursive t as (
  select ae.id, ae.id as child_id, 0 cntr 
  from a 
  where parent_id = 12 
  union all
  select t.id, a.id, cntr + 1 from t 
  join a on a.parent_id = t.child_id 
  where cntr <= 100
)

select id, count(*) from t group by id
Run Code Online (Sandbox Code Playgroud)

如果深度或计数不是您想要的,也许它只是后代节点的 row_number ?将选择更改为:

select child_id, row_number() OVER (ORDER BY Child_Id) FROM t;
Run Code Online (Sandbox Code Playgroud)