在保持结构的同时对树进行排序

| 我有一棵使用物化路径的树。 该表类似于:
+-------------+--------+----------+-------+
| path        | depth  | children | score |
+-------------+--------+----------+-------+
| 0001        | 1      | 3        | 5     |
| 00010001    | 2      | 0        | -3    |
| 00010002    | 2      | 0        | 27    |
| 00010003    | 2      | 0        | 10    |
| 0002        | 1      | 2        | 12    |
| 00020001    | 2      | 0        | 0     |
| 00020002    | 2      | 1        | 3     |
| 00020002001 | 3      | 0        | 1     |
+-------------+--------+----------+-------+
我想按
score
列进行排序,同时保持树的结构。 重要的是孩子在父母之下。
+-------------+--------+----------+-------+
| path        | depth  | children | score |
+-------------+--------+----------+-------+
| 0002        | 1      | 2        | 12    |
| 00020002    | 2      | 1        | 3     |
| 00020002001 | 3      | 0        | 1     |
| 00020001    | 2      | 0        | 0     |
| 0001        | 1      | 3        | 5     |
| 00010002    | 2      | 0        | 27    |
| 00010003    | 2      | 0        | 10    |
| 00010001    | 2      | 0        | -3    |
+-------------+--------+----------+-------+
path
列仅在数据库中使用,因此不必是连续的。 我目前使用的SQL对树进行排序,因此可以构建它:
SELECT path, depth, children, score FROM mytable ORDER BY path ASC
    
已邀请:
        您将需要一个递归查询和一个窗口函数。它看起来类似于:
with recursive
ordered_tree as (
select tree.*,
       array[row_number() over w] as score_path
from   tree
where  depth = 1
window w as (order by tree.score desc)
union all
select tree.*,
       parent.score_path || array[row_number() over w] as score_path
from   tree
join   ordered_tree as parent on parent.id = tree.parent_id
window w as (partition by tree.parent_id order by tree.score desc)
)
select *
from   ordered_tree
order by score_path
注意:如果您的设备很大,上述操作将相当慢...     

要回复问题请先登录注册