Suggestion for table/index structure?

From: Jeff Davis <list-pgsql-general(at)dynworks(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Suggestion for table/index structure?
Date: 2002-03-27 06:02:11
Message-ID: 0GTM0046ZBMVSD@mta6.snfc21.pbi.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I am writing an application that manages a heirarchy of projects. Each
project can have an arbitrary number of children and each child is also a
project. So, the net result is an arbitrarily deep tree.

The structure for the project table seemed easy enough:
create table project (
id int primary key,
parent_id int references project(id),
...
);

And I see no problem with that. However, I'd like to be able to aggregate all
of the data from any project. For example, I would like to be able to add up
all the hours of any project plus any of that project's children. That seems
like quite an expensive, recursive algorithm that the database would need to
do for any such request. So, I came up with two solutions:

1) have a field wherein the first n bytes of data are for the highest level,
and n for the second, etc. So, you could then use as a search criteria
anything that begins with these bytes. The disadvantage here is that it would
need to have some kind of maximum number of levels, and each level would have
some maximum level of children. Although these numbers could be high, I don't
really know what I'd set them at now. Also, the more space I allotted, the
bigger an index on that attribute would be, right? Or can indexes use a
variable length key?

2) have a seperate table to list all of the parents of each record and then I
could perform joins as necessary. For example, if A is a parent of B is a
parent of C, then I would have to have in the table
(project_id,parent_id)
(B,A)
(C,B)
(C,A)

because C is a child of both A and B. Of course, this separate table would
grow large, as would an index on it. Moreover, this structure requires
another join.

Does anyone have any suggestions for efficiency and flexibility of the
structure?

Regards,
Jeff

Browse pgsql-general by date

  From Date Subject
Next Message David Stanaway 2002-03-27 07:06:37 Re: [SQL] resetting sequence
Previous Message Philip Hallstrom 2002-03-27 05:30:10 Re: resetting sequence