对树数据结构进行排序

时间:2018-03-14 10:56:59

标签: sql postgresql hierarchical-data recursive-query

我有一张这样的表:

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

  

显示器在同一父母中是相对的。

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

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

非常感谢您能帮助我。谢谢!

1 个答案:

答案 0 :(得分:2)

您需要一个递归查询来遍历树。要在每个级别上正确应用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