Re: A situation with one parent table and 3 child tables

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: JORGE MALDONADO <jorgemal1960(at)gmail(dot)com>
Cc: "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: A situation with one parent table and 3 child tables
Date: 2023-10-03 02:53:54
Message-ID: CAKFQuwZbmqeLoHBzuOkVjd4qXyNUi1tcuhf8bECK+2c-DGK9iw@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Monday, October 2, 2023, JORGE MALDONADO <jorgemal1960(at)gmail(dot)com> wrote:

> Hi,
>
> I have one parent table (*table_p*) with 3 child tables (*table_ch1*, *table_ch2
> *and *table_ch3*). Each record of the parent table can be associated with
> 1 and only 1 child table records. This means that:
>
> * Some records of the *table_p* will link to records of *table_ch1*
> * Some records of the *table_p* will link to records of *table_ch2*
> * Some records of the *table_p* will link to records of *table_ch3*
>
> At first look, this does not make very much sense to me. I thought about
> considering 3 parent tables, one for each child table. However, the 3
> parent tables would have the same exact structure and I would like to know
> if there is a workaround for this issue.
>

You are thinking of it backwards. Your chN tables will have FK pointing
back to the p table. I suggest adding some kind of type column to the p
table indicating which chN table the row belongs to. Then have the same
column on the chN table with a check constraint. The key is then the id
and that type. You can, with a bit of effort, ensure a row exists on the
chN table for every row on the p table but it is circular so must be
deferred in enforcement.

David J.

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2023-10-03 03:03:04 Re: A situation with one parent table and 3 child tables
Previous Message Gareth Evans 2023-10-02 21:46:00 Re: A situation with one parent table and 3 child tables