gpt4 book ai didi

sql - 排序树数据结构

转载 作者:行者123 更新时间:2023-11-29 14:32:40 24 4
gpt4 key购买 nike

我有一个这样的表:

CREATE TABLE tree ( 
id integer NOT NULL,
name character varying(50) NOT NULL,
parentid integer,
displayorder integer NOT NULL,
CONSTRAINT tree_id PRIMARY KEY (id)
)

enter image description here

The displayorders are relative in the same parent.

我坚持对这些数据进行排序以获得如下输出:

1 -> 1.1 -> 1.1.1 -> 1.1.2 -> 1.1.3 -> 1.2 -> 1.3 -> 2 -> 3

如果你能帮助我,我将不胜感激。谢谢!

最佳答案

您需要一个递归查询来遍历树。要在每个级别上正确应用 displayorder,您还需要收集每个节点的路径,以便进行排序:

with recursive all_nodes as (
select id, name, parentid, displayorder, array[id] as path
from tree
where parentid is null
union all
select c.id, c.name, c.parentid, c.displayorder, p.path||c.id
from tree c
join all_nodes p on c.parentid = p.id
)
select id, name
from all_nodes
order by path, displayorder;

在线示例:http://rextester.com/MJEL66144

关于sql - 排序树数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49275912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com