顺序sql结果,其中引用同一表上另一条记录的每条记录都位于引用的记录之后

edqdpe6u  于 2021-08-01  发布在  Java
关注(0)|答案(2)|浏览(345)

我有以下数据:

id, parent_id
1, 3
2, null
3, 2
4, 2

其中parent\u id是对同一表的引用。
我需要对这些列进行排序,以便每个记录都在其父记录之后(不一定紧跟其后)。
所以我期望这个结果:

id, parent_id
2, null
3, 2
1, 3
4, 2

我猜在没有任何显著模式更改的情况下,没有一种干净高效的方法可以做到这一点,但万一有人能想到一种方法,我在这里问这个问题。
一种可能的方法是执行多个查询,其中每次父项id必须出现在前面的查询结果之一中。但这不是很有效。

8dtrkrch

8dtrkrch1#

您将需要递归来完成此任务:

with recursive hier as (
  select *, 0 as hlevel
    from idparent
   where parent_id is null
  union all
  select c.*, p.hlevel + 1
    from hier p
    join idparent c on p.id = c.parent_id
)
select * from hier
 order by hlevel;

 id | parent_id | hlevel 
----+-----------+--------
  2 |           |      0
  3 |         2 |      1
  4 |         2 |      1
  1 |         3 |      2
(4 rows)
dddzy1tm

dddzy1tm2#

我认为最安全的方法是使用递归的cte来计算每个路径 id . 那就分类:

with recursive cte as (
      select id, parent_id,  array[id] as path
      from t
      where parent_id is null
      union all
      select t.id, t.parent_id, path || array[t.id]
      from cte join
           t
           on cte.id = t.parent_id
     )
select *
from cte
order by path;

这是一把小提琴。

相关问题