Re: query to select a linked list - Mailing list pgsql-sql

From Achilleas Mantzios
Subject Re: query to select a linked list
Date
Msg-id 200705091631.46660.achill@matrix.gatewaynet.com
Whole thread Raw
In response to query to select a linked list  (Louis-David Mitterrand <vindex+lists-pgsql-sql@apartia.org>)
List pgsql-sql
Στις Τετάρτη 09 Μάιος 2007 15:55, ο/η Louis-David Mitterrand έγραψε:
> Hi,
>
> To build a threaded forum application I came up the following schema:
>
> forum
> ------
> id_forum | integer| not null  default
> nextval('forum_id_forum_seq'::regclass) id_parent| integer|
> subject  | text   | not null
> message  | text   |
>
> Each message a unique id_forum and an id_parent pointing to the replied
> post (empty if first post).
>
> How can I build an elegant query to select all messages in a thread?
>

Your question is about storing hierarchies in postgresql.
One way is to use the genealogical approach, where we store for
any node the path to its root.
I have used this technique to store description of tanker vessels machinery
(over 1M items) and the plan maintenance on them, and the performance is very
good, while the representation is highly intuitive and flexible,
unlike some wierd approcahes i have hit on.
When i did a small research on the complexity/index usage on various
operations (UPDATE, INSERT, DELETE, SELECT), the performance
was at least as good as the "nested pair" approch that many seemed to
promote.

You add a column "parents" (rather than just the parentid) as an integer[].
For every node you store the path to the root node starting from the most
immediate ancestor.

Then you just make an index on this column using the intarray contrib package.
Then you can easily query for nodes under a specific node, or for nodes just
one level below a specific node, nodes with no descendents (leaf nodes)
etc...

Of course you could do smth simpler, but in the long run,
representing data in the correct way will certainly pay off.

> Thanks,
>
> ---------------------------(end of broadcast)---------------------------
> TIP 1: if posting/reading through Usenet, please send an appropriate
>        subscribe-nomail command to majordomo@postgresql.org so that your
>        message can get through to the mailing list cleanly

--
Achilleas Mantzios


pgsql-sql by date:

Previous
From: Louis-David Mitterrand
Date:
Subject: Re: query to select a linked list
Next
From: Louis-David Mitterrand
Date:
Subject: Re: query to select a linked list