小编tha*_*ngh的帖子

如何在使用RECURSIVE选择后代的Postgres查询中打印深度级别?

我有一个persons包含列的表parent_id,它引用同一个表中的另一行.假设这是逻辑层次结构:

          P1
  P2      P3      P4
P5  P6  P7  P8  P9  P10
Run Code Online (Sandbox Code Playgroud)

我编写了一个查询,打印给定节点的所有父节点,以及节点上方的高度,它似乎工作正常:

WITH
RECURSIVE ancestors AS (
  SELECT id, parent_id
    FROM persons
    WHERE id = 8
  UNION
    SELECT p.id, p.parent_id
      FROM persons p
      INNER JOIN ancestors
        ON
          p.id = ancestors.parent_id
  )
SELECT persons.id, persons.name,
      ROW_NUMBER() over () as height
  FROM ancestors
  INNER JOIN persons
  ON
    ancestors.id = persons.id
  WHERE
    persons.id <> 8
Run Code Online (Sandbox Code Playgroud)

结果:

  id   |    name     | height 
-------+-------------+---------
    3  | P3          |      1
    1  | …
Run Code Online (Sandbox Code Playgroud)

postgresql tree recursion depth

6
推荐指数
1
解决办法
3676
查看次数

标签 统计

depth ×1

postgresql ×1

recursion ×1

tree ×1