X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [64.117.224.130]) by svr1.postgresql.org (Postfix) with ESMTP id 2B559D1C4D6 for ; Wed, 13 Aug 2003 11:41:04 +0000 (GMT) Received: from svr1.postgresql.org ([64.117.224.193]) by localhost (neptune.hub.org [64.117.224.130]) (amavisd-new, port 10024) with ESMTP id 08952-05 for ; Wed, 13 Aug 2003 08:39:31 -0300 (ADT) Received: from fzkmail2.fzk.de (fzkmail2.fzk.de [141.52.27.52]) by svr1.postgresql.org (Postfix) with SMTP id 37106D1C4CA for ; Wed, 13 Aug 2003 08:40:52 -0300 (ADT) Received: FROM resy5.fzk.de BY fzkmail2.fzk.de ; Wed Aug 13 13:40:54 2003 +0200 Received: œby rodos.fzk.de with ESMTP (8.8.6 (PHNE_17135)/8.7.1) id NAA25260; Wed, 13 Aug 2003 13:40:53 +0200 (METDST) Message-ID: <3F3A23C5.A6E3B03B@rodos.fzk.de> Date: Wed, 13 Aug 2003 13:40:53 +0200 From: Christoph Haller X-Mailer: Mozilla 4.77 [en] (X11; U; HP-UX B.10.20 9000/780) X-Accept-Language: en MIME-Version: 1.0 To: pgsql-sql@postgresql.org, vwu98034@lycos.com Subject: Re: INSERT INTO ... SELECT Content-Type: text/plain; charset=iso-8859-2 Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at postgresql.org X-Amavis-Alert: BAD HEADER Non-encoded 8-bit data (char 9C hex) in message header 'Received' Received: \234by rodos.fzk.de... ^ X-Archive-Number: 200308/126 X-Sequence-Number: 14742 > > Coincidentally, I have a very similar case using some twists. > > The table I want to insert data is something like > > table A ( > user01 int, > user02 int, > ... > primary key (user01, user02), > CHECK ( user01 < user02 ) > ); > > And the user table is: > > tabe user_table ( > user int constraint pk_user primary key UNIQUE, --PK > ..., > email varchar(25) not null, > ... > }; > > In the insertion statement, the user02 is obtained by a subselect statement: "select user from user where email=?". > > There may not exist the email in the user table. And if yes, the check condition may not be met. If the condition is n ot met, the two user IDs need to be switched. > > How the query shall be construted? > > Thanks for any suggestions. > I'd say this conditional insert into user02 column can be done by a PL/pgSQL function combined by CASE statements. I'm thinking of something like (untested of course) INSERT INTO ... SELECT CASE WHEN user01 < get_user02(email=?) THEN user01 ELSE get_user02(email=?) END, CASE WHEN user01 < get_user02(email=?) THEN get_user02(email=?) ELSE user01 END, ... FROM table A ... ; You might think calling the function four times is a waste, but as far as I understand it PL/pgSQL functions are run via prepared execution plans (see PL/pgSQL - SQL Procedural Language - Overview), so it shouldn't be too bad. Don't know what to do about > There may not exist the email in the user table. Insert a NULL? HTH Regards, Christoph