Re: Need help with a special JOIN

From: Samuel Gendler <sgendler(at)ideasculptor(dot)com>
To: Andreas <maps(dot)on(at)gmx(dot)net>
Cc: "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Need help with a special JOIN
Date: 2012-09-29 17:32:09
Message-ID: CAEV0TzB=AS5gEYmuk9c87qXRpJPSt6qD=751BJGw0tPjw6TzDw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Sat, Sep 29, 2012 at 9:02 AM, Andreas <maps(dot)on(at)gmx(dot)net> 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?
>
>
I'm not sure it is any more elegant than the kind of solution you suggest,
but this works:

# select id, name, value from
(select *, count(o.id) over (partition by o.id) as total from objects o
join attributes a on a.object_id = o.id or a.object_id = 0) q
where total = 1 or object_id != 0;
id | name | value
----+------+-------
1 | A | 42
2 | B | 99
3 | C | 42

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message David Johnston 2012-09-29 17:33:56 Re: Need help with a special JOIN
Previous Message Andreas 2012-09-29 16:02:23 Need help with a special JOIN