X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [64.117.224.192]) by svr1.postgresql.org (Postfix) with ESMTP id 9B3FACC722 for ; Thu, 17 Jul 2003 01:33:55 +0000 (GMT) Received: from svr1.postgresql.org ([64.117.224.193]) by localhost (svr4.postgresql.org [64.117.224.192]) (amavisd-new, port 10024) with ESMTP id 42071-07 for ; Thu, 17 Jul 2003 01:34:18 +0000 (GMT) Received: from chico.benjamindsmith.com (adsl-63-195-17-22.dsl.chic01.pacbell.net [63.195.17.22]) by svr1.postgresql.org (Postfix) with ESMTP id 01432CC71F for ; Wed, 16 Jul 2003 22:33:53 -0300 (ADT) Received: from bug2 (bug2.benjamindsmith.com [10.254.254.5]) by chico.benjamindsmith.com (8.11.6/8.11.6) with ESMTP id h6H1YGj21309 for ; Wed, 16 Jul 2003 18:34:16 -0700 Content-Type: text/plain; charset="us-ascii" From: Benjamin Smith Reply-To: bens@effortlessis.com Organization: Effortless Information Systems To: pgsql-sql@postgresql.org Subject: Join table with itself for heirarchial system? Date: Wed, 16 Jul 2003 18:34:08 -0700 User-Agent: KMail/1.4.3 X-Message: Using Microsoft Outlook makes you vulnerable to many viruses. MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Message-Id: <200307161834.08104.bens@effortlessis.com> X-MailScanner: Found to be clean X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200307/287 X-Sequence-Number: 14401 Can you query a set of nested entries to simulate a heirarchial system with a single query? I'm building a nested category table with a definition like below" CREATE TABLE category ( id serial, parent integer not null, title varchar); Idea is that we can "nest" categories so that we have id parent title ---------------------------------------------- 1 0 Clothing 2 1 Shirts 3 1 Pants 4 1 Socks 5 4 Male 6 4 Silk So that, for example, id 6 would be Clothing -> Socks -> Silk. So far, I've only been able to derive this with 3 queries - 1 to get the parent for id #6 (Silk) another to get the parent for id #4 (Socks) and finally for id #1 (Clothing) and since parent ==0 I stop. This seems wasteful - can this be done in a single query?