X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 9A4344758F1 for ; Tue, 15 Apr 2003 20:00:18 -0400 (EDT) Received: from boromir.vpop.net (dns1.vpop.net [207.178.248.2]) by postgresql.org (Postfix) with ESMTP id 69AF9475458 for ; Tue, 15 Apr 2003 20:00:17 -0400 (EDT) Received: from aragorn.vpop.net (c5cust187.starstream.net [206.170.161.187]) by boromir.vpop.net (Postfix) with ESMTP id 908B73A6152; Tue, 15 Apr 2003 17:00:12 -0700 (PDT) Subject: Re: reversion? Recursion question From: Brad Hilton To: Patrick Hatcher Cc: pgsql-sql@postgresql.org In-Reply-To: References: Content-Type: text/plain Organization: Message-Id: <1050451222.13093.22.camel@aragorn.vpop.net> Mime-Version: 1.0 X-Mailer: Ximian Evolution 1.2.4 Date: 15 Apr 2003 17:00:22 -0700 Content-Transfer-Encoding: 7bit X-Spam-Status: No, hits=-38.0 required=5.0 tests=BAYES_10,EMAIL_ATTRIBUTION,IN_REP_TO,QUOTED_EMAIL_TEXT, REFERENCES,REPLY_WITH_QUOTES,USER_AGENT_XIMIAN autolearn=ham version=2.50 X-Spam-Level: X-Spam-Checker-Version: SpamAssassin 2.50 (1.173-2003-02-20-exp) X-Archive-Number: 200304/244 X-Sequence-Number: 12945 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