self referencing table structure and constraints

Поиск
Список
Период
Сортировка
От Matthew Hixson
Тема self referencing table structure and constraints
Дата
Msg-id D29E56BE-0DC7-11D9-AE4C-000A95D05926@poindextrose.org
обсуждение исходный текст
Ответы Re: self referencing table structure and constraints  (Stephan Szabo <sszabo@megazone.bigpanda.com>)
Список pgsql-general
I have a categories table that contains a FK to another category in the
same table, creating a hierarchy.  At the very top is this row:

  category_id | name |       description       | parent_id
-------------+------+-------------------------+-----------
            1 | ROOT | The top level category. |         0

There is no record with category_id 0 because ROOT is at the top of the
tree.  I'd like to set up a constraint on this table so that every
category has to have a parent_id and it would be impossible to delete a
category if it had subcategories.  The problem is that this root
category violates that constraint.  Is there a way to setup the
constraint so that it constrains every record except for forcing the
root category to point at a real parent category?
   I thought of pointing ROOT to itself, but since we have some
recursive code that starts at a given category id and moves up the tree
it will hit the ROOT category and loop forever.  I'd like to fix this
by constraining the database so that even working from psql it would be
difficult to damage this table by hand.
   Are there any widely used techniques for dealing with this type of
constraint?
   Thanks,
    -M@


В списке pgsql-general по дате отправления:

Предыдущее
От: "Joshua D. Drake"
Дата:
Сообщение: Re: Returning recordsets with functions
Следующее
От: Stephan Szabo
Дата:
Сообщение: Re: Returning recordsets with functions