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