X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 45AD7D1B1C9 for ; Tue, 22 Jun 2004 15:10:35 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 01552-03 for ; Tue, 22 Jun 2004 18:10:32 +0000 (GMT) Received: from wolff.to (wolff.to [66.93.249.74]) by svr1.postgresql.org (Postfix) with SMTP id 3C034D1B1FD for ; Tue, 22 Jun 2004 15:10:30 -0300 (ADT) Received: (qmail 20959 invoked by uid 500); 22 Jun 2004 18:16:49 -0000 Date: Tue, 22 Jun 2004 13:16:49 -0500 From: Bruno Wolff III To: Matthew Nuzum Cc: pgsql-sql@postgresql.org Subject: Re: matching rows differing only by fkey,pkey Message-ID: <20040622181649.GB20086@wolff.to> Mail-Followup-To: Matthew Nuzum , pgsql-sql@postgresql.org References: <20040622172704.GA19163@wolff.to> <200406221740.i5MHe6nb015623@ms-smtp-02.tampabay.rr.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <200406221740.i5MHe6nb015623@ms-smtp-02.tampabay.rr.com> User-Agent: Mutt/1.5.6i X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200406/210 X-Sequence-Number: 18155 On Tue, Jun 22, 2004 at 13:40:03 -0400, Matthew Nuzum wrote: > The end result is to duplicate the data for a particular record in table > "a" so that all of it's related data in tables "b" and "c" is duplicated. > Where "b" is the middle table in a many to many relationship. For example, > > - a ---- - b ---- - c ---- > aid <--+ bid <--+ cid > data1 +-->aid +-->bid > data2 field1 info1 > date3 field2 info2 > > SELECT a.*,b.*,c.* from a,b,c where b.aid = a.aid and c.bid = b.bid; > > So, the goal is to duplicate an object that is made up of the data stored > across these three tables. > > Any suggestions? First duplicate the record in table a. Its key will be in a sequence named something like a_aid_seq. Then for each record in table b with aid equal to the key of the record being duplicated do the following: Duplicate the current record in table b. Its aid should be currval('a_aid_seq'). The new bid will be available in b_bid_seq. The old bid will need to be noted by the program. Then you can duplicate all of the records pointing to this record in table c with something like the following: INSERT INTO c (bid, info1, info2) SELECT currval('b_bid_seq'), info1, info2 FROM c WHERE bid = the_old_bid; Offhand I can't think of a way to avoid using a procedural language to walk through the b table so that you can easily keep track of which new bid corresponds to which old bid. However, writing a perl script or plsql function to do this for you shouldn't be difficult.