Received: from localhost (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id 57293632C4C for ; Fri, 10 Jul 2009 09:34:13 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by localhost (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 35236-01 for ; Fri, 10 Jul 2009 09:33:54 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from ciao.gmane.org (main.gmane.org [80.91.229.2]) by mail.postgresql.org (Postfix) with ESMTP id C317162FBE6 for ; Fri, 10 Jul 2009 09:34:01 -0300 (ADT) Received: from list by ciao.gmane.org with local (Exim 4.43) id 1MPFIc-0005xp-Na for pgsql-sql@postgresql.org; Fri, 10 Jul 2009 12:33:58 +0000 Received: from srv.protecting.net ([212.126.218.242]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Fri, 10 Jul 2009 12:33:58 +0000 Received: from hari.fuchs by srv.protecting.net with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Fri, 10 Jul 2009 12:33:58 +0000 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Harald Fuchs Subject: Re: WITH RECURSION output ordering with trees Date: Fri, 10 Jul 2009 14:33:48 +0200 Lines: 37 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Complaints-To: usenet@ger.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:zczoI8F0948gey7fRTxcJVa+YIg= X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200907/59 X-Sequence-Number: 32800 In article , "Philippe Lang" writes: > Thanks for your answer. Si there a built-in function that would allow > generating the sort path based on the value of the lookup column, > instead of the id, which has no meaning at all? > If yes, we would get instead: > depth | id | lookup | parent_id > -------+-----+--------+----------- > 0 | 1 | a1 | > 1 | 2 | b11 | 1 > 2 | 645 | c111 | 2 > 2 | 823 | c112 | 2 > 2 | 243 | c113 | 2 > 1 | 6 | b12 | 1 > 2 | 845 | c121 | 6 > 2 | 583 | c122 | 6 > 1 | 9 | b13 | 1 > 2 | 10 | c131 | 9 Try this: WITH RECURSIVE parse_tree (depth, id, lookup, parent_id, path) AS ( SELECT 0, parent.id, parent.lookup, parent.parent_id, parent.lookup::text FROM recursion AS parent WHERE parent_id IS NULL UNION ALL SELECT parent.depth + 1, child.id, child.lookup, child.parent_id, parent.path || '.' || child.lookup FROM parse_tree parent JOIN recursion AS child ON child.parent_id = parent.id ) SELECT depth, id, lookup, parent_id FROM parse_tree ORDER BY path