Re: Help with INSERT into 2 tables

From: Roland Roberts <roland(at)astrofoto(dot)org>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Help with INSERT into 2 tables
Date: 2001-11-15 16:44:44
Message-ID: m2g07ggf0j.fsf@tycho.rlent.pnet
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

>>>>> "Gintas" == Gintas <gntrs(at)hotmail(dot)com> writes:

Gintas> I am new to SQL and don't know how to INSERT records to 2 tables.
Gintas> The first table:

Gintas> CREATE TABLE aaaa ( aaaaid SERIAL PRIMARY KEY,
Gintas> text VARCHAR(20)
Gintas> );

Gintas> Second table:

Gintas> CREATE TABLE bbbb ( bbbbid SERIAL PRIMARY KEY,
Gintas> aaaaid INTEGER REFERENCES aaaa (aaaaid) ON
Gintas> DELETE CASCADE,
Gintas> sometext VARCHAR(200)
Gintas> );

Gintas> I want to insert related records to both table. The
Gintas> problem is that in order to insert record to the second
Gintas> table it's necessary to know "aaaaid" field from the first
Gintas> table("text" is not UNIQUE):

Gintas> INSERT INTO aaaa (text) VALUES ('Some info');
Gintas> INSERT INTO bbbb (aaaaid, sometext) VALUES (?????, 'Some text');

Gintas> How is it possible to do that? (I am inserting this from
Gintas> JAVA).

The normal way to do this is to explicitly pull out the serial value
from the underlying sequence. I.e., something like this

select nextval('aaaa_aaaaid_seq');
begin transaction;
insert into aaaa (aaaaid, text) values ($seqno, 'Some info');
insert into bbbb (aaaaid, sometext) VALUES ($seqno, 'Some text');
end transaction;

where you use the jdbc calls to retrieve the result from the "select
nextval...".

SERIAL types are not quite as useful as people tend to think unless
you have the ability to identify the value from some other
characteristic. If the ID is purely an ID and you don't care about
its value, you still have to have a way of *finding* it.

roland
--
PGP Key ID: 66 BC 3B CD
Roland B. Roberts, PhD RL Enterprises
roland(at)rlenter(dot)com 76-15 113th Street, Apt 3B
roland(at)astrofoto(dot)org Forest Hills, NY 11375

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Roland Roberts 2001-11-15 16:49:12 PL/pgSQL examples NOT involving functions
Previous Message Bryan White 2001-11-15 16:37:55 How to best grab a chunk of Ids from a sequence