Received: from mail.astrofoto.org (dsl092-102-177.nyc2.dsl.speakeasy.net [66.92.102.177]) by postgresql.org (8.11.3/8.11.4) with ESMTP id fAFGiem20935 for ; Thu, 15 Nov 2001 11:44:40 -0500 (EST) (envelope-from roland@astrofoto.org) Received: (from roland@localhost) by mail.astrofoto.org (8.11.6/8.11.6) id fAFGijG15464; Thu, 15 Nov 2001 11:44:45 -0500 To: pgsql-sql@postgresql.org Subject: Re: Help with INSERT into 2 tables References: <558f8e45.0111130542.1e617f99@posting.google.com> From: Roland Roberts Date: 15 Nov 2001 11:44:44 -0500 In-Reply-To: <558f8e45.0111130542.1e617f99@posting.google.com> Message-ID: Lines: 51 User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.0.105 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Archive-Number: 200111/215 X-Sequence-Number: 5598 >>>>> "Gintas" == Gintas 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@rlenter.com 76-15 113th Street, Apt 3B roland@astrofoto.org Forest Hills, NY 11375