A path through a tree

maillist@remo.demon.co.uk

From: "Neil Burrows" <maillist@remo.demon.co.uk>
To: <pgsql-sql@postgreSQL.org>
Date: 1999-01-12T14:34:16Z
Lists: pgsql-sql
Hi,

OK, I have a feeling that this not something that can be done with SQL but I
may as well give it a shot.

Say you have a table with the following columns:

id	 int4 NOT NULL UNIQUE
parent int4
value  varchar(8)

and each entry represents a node in a tree.  So the top most node will have
no parent, and the next nodes will have the 1st node's id as their parent
etc etc etc.

If I have a leaf node, is there a SELECT statement that will give me all the
parent ids on the way to the root?  (See diagram below for a different
[probably not better] description).

The tree can be of arbitrary depth.

where i = id and p = parent

		i = 1
		p = NULL
              |
		  |
	  +-----+-----+
	  |		  |
	i = 2		i = 3
	p = 1		p = 1
			  |
			  |
 		  +-----+-----+
		  |		  |
		i = 4		i = 5
		p = 3		p = 3


So if I wanted to find all the parent ids from node with index 5 to root I'd
get (3,1)?

As I say, I doubt there is a simple select that can do this but thought I
may as well ask.

Thanks in advance,

Neil Burrows