From: Bruce Stephens <bruce@cenderis.demon.co.uk>
To: pgsql-sql@postgresql.org
Subject: Re: [SQL] A path through a tree
Date: 12 Jan 1999 19:09:55 +0000
Message-ID: <m3sodgb94s.fsf@cenderis.demon.co.uk> (raw)
References: <000c01be3e38$a1d4a170$c6cb9284@towhee.gssec.bt.co.uk>
"Neil Burrows" <maillist@remo.demon.co.uk> writes:
> 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).
Alas, no. (I think, anyway. There wasn't the last time I looked!)
What you want is proposed as RECURSIVE UNION, or RECURSIVE JOIN, or
something. For reasonably static trees, you can set things up so that
the answer is straightforward: encode leaves with suitable distinct
values, and have "min" and "max" columns which encode the minimum and
maximum values in the subtrees.
There's an FAQ for one of the commercial databases which explains this
(I forget which), and Joe Celko's "SQL for Smarties" also describes
issues like this.
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-sql@postgresql.org
Cc: bruce@cenderis.demon.co.uk
Subject: Re: [SQL] A path through a tree
In-Reply-To: <m3sodgb94s.fsf@cenderis.demon.co.uk>
References: <000c01be3e38$a1d4a170$c6cb9284@towhee.gssec.bt.co.uk> <m3sodgb94s.fsf@cenderis.demon.co.uk>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox