Re: Query Question

Поиск
Список
Период
Сортировка
От Tom Lane
Тема Re: Query Question
Дата
Msg-id 6399.1339803889@sss.pgh.pa.us
обсуждение исходный текст
Ответ на Query Question  (Henry Ramsey <henry.ramsey.pcpa@statefarm.com>)
Список pgsql-novice
Henry Ramsey <henry.ramsey.pcpa@statefarm.com> writes:
> I have created 3 tables, the parent table has a primary key(pmt_id)
> which is generated by a sequence object which is tied to this table.
> The 2nd table paid_policy is a child to the first table and has a
> primary key of pmt_id, (which is the FK to the 1st table), plcy_num
> and rqst_id.  The third table which is a child to the 2nd table has a
> primary key of pmt_id, plcy_num, rqst_id, and pmt_tstmp.

FWIW, this use of "child" doesn't square with the way the term is
typically used in Postgres.  I think you just mean that the one table
has an FK reference to the other.

> When inserting a row into the parent the sequence number is generated
> and returned by the statement below; however, I have not been able to
> figure out a way to capture this id to insert it in the 3rd table
> since it is part of the key.

Since you're relying on WITH RETURNING anyway, can't you chain several
such WITHs together?  Something like this:

WITH ins1 AS (INSERT INTO t1 VALUES(...) RETURNING ...),
     ins2 AS (INSERT INTO t2 SELECT ... FROM ins1 RETURNING ...)
INSERT INTO t3 SELECT ... FROM ins2;

A quick test says that this works unsurprisingly.  You do need to have
all the values from t1 that you need in t3 be also inserted into t2
so that you can return them up from ins2.  (If you had to, you could
probably join the results of ins1 and ins2 to overcome that, but I'd
personally avoid a join if I could.)

In any case, I'd advise using INSERT ... SELECT rather than the hack of
sub-selects in a VALUES list.  The sub-select method doesn't scale
nicely when you need more than one value from the WITH rows.

            regards, tom lane

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

Предыдущее
От: Jeff Davis
Дата:
Сообщение: Re: create table from regular expressions applied to rows of multiple tables
Следующее
От: Vibhor Kumar
Дата:
Сообщение: Re: Query Question