Received: from localhost (maia-2.hub.org [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id F3AB79FB35D for ; Sun, 17 Jun 2007 06:05:38 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 93411-09 for ; Sun, 17 Jun 2007 06:05:32 -0300 (ADT) X-Greylist: delayed 00:25:11.708059 by SQLgrey-1.7.4 Received: from svr4.postgresql.org (svr4.postgresql.org [66.98.251.159]) by postgresql.org (Postfix) with ESMTP id 72BDC9FB57B for ; Sun, 17 Jun 2007 06:05:35 -0300 (ADT) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.3 Received: from elasmtp-banded.atl.sa.earthlink.net (elasmtp-banded.atl.sa.earthlink.net [209.86.89.70]) by svr4.postgresql.org (Postfix) with ESMTP id F3D565AF041 for ; Sun, 17 Jun 2007 08:40:22 +0000 (GMT) Received: from [69.86.105.158] (helo=[192.168.0.102]) by elasmtp-banded.atl.sa.earthlink.net with asmtp (Exim 4.34) id 1HzqIw-0005Sa-CB for pgsql-sql@postgresql.org; Sun, 17 Jun 2007 04:40:14 -0400 Message-ID: <4674F357.5040409@bucksvsbytes.com> Date: Sun, 17 Jun 2007 04:39:51 -0400 From: John Gunther User-Agent: Thunderbird 1.5.0.12 (Windows/20070509) MIME-Version: 1.0 To: pgsql-sql@postgresql.org Subject: joining a table whose name is stored in the primary record Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-ELNK-Trace: 012f15a0baae39ad94f5150ab1c16ac0c864d17e3813b99a3eb184352da98f90c51c34307e6b8307350badd9bab72f9c350badd9bab72f9c350badd9bab72f9c X-Originating-IP: 69.86.105.158 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.001 tagged_above=0 required=5 tests=BAYES_50=0.001 X-Spam-Level: X-Archive-Number: 200706/117 X-Sequence-Number: 28607 I've tried everything I can think of here to join records when the join table varies and is named in the primary record, but to no avail. Here's an example with all non-essentials stripped out. I have 3 tables: create table zip ( id serial primary key, name text, parent_tbl text, parent_id int ); create table city ( id serial primary key, name text ); create table county ( id serial primary key, name text ); The zip table has 2 records as follows: id|name|parent_tbl|parent_id ----------------------------- 1 |10001|city |12 2 |19999|county |99 The possible parent tables can be many more than the two examples, city and county. In a single psql statement, I want to retrieve zip records joined with the record of their respective parents. The join id is in zip.parent_id but the obvious issue is that the join table varies and is only found in zip.parent_tbl. Obviously, I can select from zip, then step through the results and select the joined data separately for each zip result. How can I get these results in one statement? I've tried writing SQL functions and using subqueries without success. I think I need someone to point me in the right conceptual direction. Thanks. John Gunther Bucks vs Bytes Inc