Storing a tree

From: Antonio Fiol Bonnín <fiol(at)w3ping(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Storing a tree
Date: 2001-11-08 12:31:10
Message-ID: 3BEA7B0E.A6EFA5E6@w3ping.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-jdbc

Hello,

I have found a problem today to which I am unable to find the solution.
I write to this list looking for help.

I have been using PostgreSQL for about a year or so, and I manage a
quite large database. I usually design extensions to it, create new
tables and views, indexes, and many more. In short, it's not my first
database application.

I would like to store a tree in the database. A tree much like a
directory tree, with un unknown depth.

However, in my case, the order of the leafs (left to right) is
important.

I tried to implement the tree as a table:

CREATE TABLE tree ( father_id int, son_id int );

Then, I can easily find all sons for a father. Even in correct order:

SELECT son_id FROM tree WHERE father_id=1234 ORDER BY son_id;

Even if I wish to use another ordering, I could:

CREATE TABLE tree (father_id int, son_id int );
CREATE TABLE people ( person_id int, name text, age int );
and then
SELECT people.person_id, people.name, people.age FROM tree, people WHERE
tree.father_id=1234 AND tree.son_id=people.person_id
ORDER BY people.age;

For one generation, all works well. I could also extend that up to 2
generations, but not until the sons have no more sons. Could someone
help me find a way to output the data in the following way ?

Peter, 90
John (Peter's son), 65
Richard (John's son), 44
William (John's son), 45
Philip (William's son), 20
Tony (Peter's son), 70
Other (Tony's son), 50

Two things are crucial: ORDER and MULTIPLE GENERATIONS.

The genealogic example is given only to avoid explaining the complexity
of our application design. We are a company specialized in web server
performance monitoring, so genealogic studies is not our core business
;-) This way, I thought I could simplify the understanding of the
problem.

I am certain that others have been faced to similar problems, so
probably someone may help me.

Thank you all for any lights you can shed on this problem.

Antonio Fiol

P.S. Other similar problems I can think of:

Relation Boss --> Employee (though depth is finite in this case).

History of people owning an object (though only one "son" per "father",
so no ordering issue)

A directory tree (without any files).

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Mirko Zeibig 2001-11-08 13:24:03 Re: Why is there no option -U with pg_dump?
Previous Message Martín Marqués 2001-11-08 12:02:11 Re: [HACKERS] PostgreSQL v7.2b2 Released

Browse pgsql-jdbc by date

  From Date Subject
Next Message Erwin Ambrosch 2001-11-08 13:02:39 Connection and Statement
Previous Message Peter Wasem 2001-11-08 08:19:16 Re: Memory exeception