Received: from makus.postgresql.org ([98.129.198.125]) by malur.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1TI1mW-00006p-JX for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 18:28:52 +0000 Received: from ppp248107867.ambra.ro ([86.107.248.7] helo=caido.ro) by makus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1TI1mU-0005UA-MN for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 18:28:51 +0000 Received: from localhost (localhost [127.0.0.1]) by caido.ro (Postfix) with ESMTP id 09A95141974 for ; Sat, 29 Sep 2012 21:26:29 +0000 (UTC) X-Amavis-Modified: Mail body modified (using disclaimer) - caido.ro X-Virus-Scanned: amavisd-new at caido.ro Received: from caido.ro ([127.0.0.1]) by localhost (caido.ro [127.0.0.1]) (amavisd-new, port 10026) with ESMTP id vJdCLcpGUzWD for ; Sat, 29 Sep 2012 21:26:28 +0000 (UTC) Received: from [127.0.0.1] (unknown [89.43.152.14]) by caido.ro (Postfix) with ESMTPSA id 6B793141973 for ; Sat, 29 Sep 2012 21:26:28 +0000 (UTC) Message-ID: <50673DDD.5070605@caido.ro> Date: Sat, 29 Sep 2012 21:28:45 +0300 From: Victor Sterpu User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120907 Thunderbird/15.0.1 MIME-Version: 1.0 To: pgsql-sql@postgresql.org Subject: Re: Need help with a special JOIN References: <50671B8F.4090504@gmx.net> In-Reply-To: <50671B8F.4090504@gmx.net> Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201209/67 X-Sequence-Number: 36869 This is a way to do it, but things will change if you have many attributes/object SELECT o.*, COALESCE(a1.value, a2.value) FROM objects AS o LEFT JOIN attributes AS a1 ON (a1.object_id = o.id) LEFT JOIN attributes AS a2 ON (a2.object_id = 0); On 29.09.2012 19:02, Andreas wrote: > Hi, > > asume I've got 2 tables > > objects ( id int, name text ) > attributes ( object_id int, value int ) > > attributes has a default entry with object_id = 0 and some other > where another value should be used. > > e.g. > objects > ( 1, 'A' ), > ( 2, 'B' ), > ( 3, 'C' ) > > attributes > ( 0, 42 ), > ( 2, 99 ) > > The result of the join should look like this: > > object_id, name, value > 1, 'A', 42 > 2, 'B', 99 > 3, 'C', 42 > > > I could figure something out with 2 JOINs, UNION and some DISTINCT ON > but this would make my real query rather chunky. :( > > Is there an elegant way to get this? > >