Need help with 'unique parents' constraint

Поиск
Список
Период
Сортировка
От Leif B. Kristensen
Тема Need help with 'unique parents' constraint
Дата
Msg-id 200509111424.04331.leif@solumslekt.org
обсуждение исходный текст
Ответы Re: Need help with 'unique parents' constraint  ("Leif B. Kristensen" <leif@solumslekt.org>)
Re: Need help with 'unique parents' constraint  ("Greg Sabino Mullane" <greg@turnstep.com>)
Список pgsql-sql
This message has also been posted to comp.databases.

I've got a problem that I can't quite wrap my head around, about adding
a constraint to my PostgreSQL genealogy database. If somebody are
interested, I've written some thoughts on the general design at
<http://solumslekt.org/forays/blue.php>.

I've got two tables, persons and relations. I need a separate relations
table for source referencing and discussion. Here are my preliminary
definitions (irrelevant columns removed):

CREATE TABLE persons (   person_id   INTEGER PRIMARY KEY,   gender      SMALLINT NOT NULL DEFAULT 0        CHECK
(genderIN (0,1,2,9)) -- ISO gender codes 
);

CREATE TABLE relations (   relation_id INTEGER PRIMARY KEY,   child_fk INTEGER REFERENCES persons (person_id),
parent_fkINTEGER REFERENCES persons (person_id),   CONSTRAINT child_parent UNIQUE (child_fk, parent_fk) 
);

Now, I want to ensure that each person_id can be assigned only one
father (gender=1) and one mother (gender=2). (Yes, this is old-
fashioned, but I'm working with 18th century people). How do I do it?

I have tried this:

ALTER TABLE relations ADD CONSTRAINT non_unique_father   CHECK (NOT EXISTS       (SELECT persons.person_id,
relations.parent_fk          FROM persons AS P, relations AS R           WHERE R.parent_fk = P.person_id           AND
P.gender= 1)); 

But psql replies with:

pgslekt=> \i install/add_unique_father_and_mother_constraint.sql
psql:install/add_unique_father_and_mother_constraint.sql:9: NOTICE:
adding missing FROM-clause entry in subquery for table "persons"
psql:install/add_unique_father_and_mother_constraint.sql:9: ERROR:
cannot use subquery in check constraint

From what I've found on Google, it looks like the "cannot use subquery
in check constraint" is a real limitation in PostgreSQL. Can I use a
trigger to achieve what I want? I'm still a little shaky on triggers
and what they can do, having quite recently converted to PostgreSQL
from a certain Swedish dinky-db.
--
Leif Biberg Kristensen
http://solumslekt.org/


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

Предыдущее
От: Trent Shipley
Дата:
Сообщение: Re: a "catch all" type ... such a thing?
Следующее
От: "Leif B. Kristensen"
Дата:
Сообщение: Re: Need help with 'unique parents' constraint