سؤال

I have a table that represents a hierarchy by referencing itself.

create table nodes (
  id integer primary key,
  parent_id integer references nodes (id),
  name varchar(255)
);

Given a specific node, I would like to find all of its parents in order, as breadcrumbs. For example, given this data:

insert into nodes (id,parent_id,name) values 
(1,null,'Root'),
(2,1,'Left'),
(3,1,'Right'),
(4,2,'LeftLeft'),
(5,2,'LeftRight'),
(6,5,'LeftRightLeft');

If I wanted to start at id=5 I would expect the result to be:

id | depth | name
-- | ----- | ----
1  | 0     | 'Root'
2  | 1     | 'Left'
5  | 2     | 'LeftRight'

I don't care if the depth column is present, but I included it for clarity, to show that there should only be one result for each depth and that results should be in order of depth. I don't care if it's ascending or descending. The purpose of this is to be able to print out some breadcrumbs that look like this:

(1)Root \ (2)Left \ (5)LeftRight
هل كانت مفيدة؟

المحلول

The basic recursive query would look like this:

with recursive tree(id, name, parent_id) as (
    select n.id, n.name, n.parent_id
    from nodes n
    where n.id = 5
    union all
    select n.id, n.name, n.parent_id
    from nodes n
    join tree t on (n.id = t.parent_id)
)
select *
from tree;

Demo: http://sqlfiddle.com/#!15/713f8/1

That will give you everything need to rebuild the path from id = 5 back to the root.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top