Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 672566354E5 for ; Tue, 20 Apr 2010 13:28:25 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 97893-03-7 for ; Tue, 20 Apr 2010 16:28:15 +0000 (UTC) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.6 Received: from lo.gmane.org (lo.gmane.org [80.91.229.12]) by mail.postgresql.org (Postfix) with ESMTP id 2F2DF636856 for ; Tue, 20 Apr 2010 13:05:59 -0300 (ADT) Received: from list by lo.gmane.org with local (Exim 4.69) (envelope-from ) id 1O4FxT-0001W7-NH for pgsql-general@postgresql.org; Tue, 20 Apr 2010 18:05:55 +0200 Received: from srv.protecting.net ([212.126.218.242]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Tue, 20 Apr 2010 18:05:55 +0200 Received: from hari.fuchs by srv.protecting.net with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Tue, 20 Apr 2010 18:05:55 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-general@postgresql.org connect(): No such file or directory From: Harald Fuchs Subject: Re: Ltree - how to sort nodes on parent node Date: Tue, 20 Apr 2010 18:05:46 +0200 Lines: 44 Message-ID: References: <59670B22-30CB-4E6E-83C8-C1D1036C9B2A@solfertje.student.utwente.nl> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Complaints-To: usenet@dough.gmane.org X-Gmane-NNTP-Posting-Host: srv.protecting.net X-Archive: encrypt User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.2 (gnu/linux) Cancel-Lock: sha1:Q4zBeo5GVdLOnOMHZvH7bdBSN8k= X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.899 tagged_above=-10 required=5 tests=BAYES_00=-1.9, FREEMAIL_FROM=0.001, T_RP_MATCHES_RCVD=-0.01, T_TO_NO_BRKTS_FREEMAIL=0.01 X-Spam-Level: X-Archive-Number: 201004/659 X-Sequence-Number: 161857 In article <59670B22-30CB-4E6E-83C8-C1D1036C9B2A@solfertje.student.utwente.nl>, Alban Hertroys writes: > 2). Drop the ltree column and go with a truly recursive approach, something like this: > CREATE TABLE node ( > category text NOT NULL PRIMARY KEY, > sort_order int NOT NULL, > parent text REFERENCES tree (category) > ON UPDATE CASCADE > ON DELETE CASCADE > ); > WITH RECURSIVE tree AS ( > SELECT * > FROM node > WHERE parent IS NULL > UNION ALL > SELECT node.* > FROM tree, node > WHERE node.parent = tree.category > ORDER BY sort_order > ) > SELECT * FROM tree; Here's a working version: WITH RECURSIVE tree (path, category, sort_order, parent) AS ( SELECT category, category, sort_order::text, parent FROM node WHERE parent IS NULL UNION ALL SELECT t.path || '.' || n.category, n.category, t.sort_order || '.' || n.sort_order, n.parent FROM tree t JOIN node n ON n.parent = t.category ) SELECT path FROM tree ORDER BY sort_order