Re: reversion? Recursion question

From: Brad Hilton <bhilton(at)vpop(dot)net>
To: Patrick Hatcher <PHatcher(at)macys(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: reversion? Recursion question
Date: 2003-04-16 00:00:22
Message-ID: 1050451222.13093.22.camel@aragorn.vpop.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Tue, 2003-04-15 at 15:41, Patrick Hatcher wrote:
> Hello,
> For lack of a better title, I need to a reverse recursion. Where I have
> the parent ID, but then I need to find all it's children, grandchildren,
> great-grandchildern, etc for the parent-id. I guess this would be like a
> directory and all its sub-directories.

You may want to look at another way of doing this. Joe Celko gives an
example of "nested sets" which allows you to select tree-like sets from
your database very efficiently. His book "SQL for Smarties" has a
chapter on this, or google for "celko sql tree" and you'll find some
articles he's written on it. Here's a link to one:
http://www.intelligententerprise.com/001020/celko.shtml.

I just converted a project from the approach you outlined to the nested
sets approach, and it has really helped. The general idea is to think
of your tree as a bunch of ovals which fall inside or next to one
another. I'll let you read his article - he explains things fairly
well.

The problem with your recursive query approach is that you'll have to do
one query per item in your tree which quickly gets out of hand. With
the nested sets approach you can get everything in one simple query. It
also allows you to do nice things like find all ancestors of a given
node (parent, grandparent, great-grandparent, etc), or find all
leaf-nodes (items that have no children). The only tricky part can be
writing the appropriate triggers to insert, remove, and move items in
your tree.

I hope this helps,
-Brad

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Adam Sherman 2003-04-16 04:38:33 Re: Percentage of Total Occurances
Previous Message George Weaver 2003-04-15 23:13:09 Re: changing column size and type.