Re: Query Question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Henry Ramsey <henry(dot)ramsey(dot)pcpa(at)statefarm(dot)com>
Cc: "pgsql-novice(at)postgresql(dot)org" <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Query Question
Date: 2012-06-15 23:44:49
Message-ID: 6399.1339803889@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Henry Ramsey <henry(dot)ramsey(dot)pcpa(at)statefarm(dot)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

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Vibhor Kumar 2012-06-16 00:10:38 Re: Query Question
Previous Message Jeff Davis 2012-06-15 23:36:08 Re: create table from regular expressions applied to rows of multiple tables