Re: Is it This Join Condition Do-Able?

From: Mischa Sandberg <mischa(dot)sandberg(at)telus(dot)net>
To: Dmitri Bichko <dbichko(at)aveopharma(dot)com>
Cc: Lane Van Ingen <lvaningen(at)esncc(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: Is it This Join Condition Do-Able?
Date: 2005-08-17 19:31:16
Message-ID: 1124307076.4303908468d72@webmail.telus.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Quoting Dmitri Bichko <dbichko(at)aveopharma(dot)com>:

> How about:
>
> SELECT a.keyfld, a.foo1, b.foo2, c.foo3
> FROM a
> LEFT JOIN b USING(keyfld)
> LEFT JOIN c USING(keyfld)

((( See response at end )))

> > -----Original Message-----
> > [mailto:pgsql-sql-owner(at)postgresql(dot)org] On Behalf Of Lane Van
> Ingen
> > Sent: Wednesday, August 17, 2005 12:55 PM
> > Subject: [SQL] Is it This Join Condition Do-Able?
> >
> > Given three tables: a, b, c ; each consist of a 'keyfld' and
> > a field called
> > 'foo':
> > tbl a tbl b tbl c
> > --------- --------- ---------
> > a.keyfld b.keyfld c.keyfld
> > a.foo1 b.foo2 c.foo3
> >
> > I want to always return all of tbl a; and I want to return
> > b.foo2 and c.foo3 if they can be joined to based on keyfld.a;
> > I know that it will involve a LEFT OUTER JOIN on table a, but
> > have not seen any examples of joins like this on 3 or more tables.
...

Having a bit of uncertainty of how LEFT JOIN associates, I tried the
following test (psql -qe), with (to me) highly surprising results.
Anyone care to comment on the third row of output?

select version();
version
-----------------------------------------------------------------------------------
PostgreSQL 8.0.3 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 3.3.3
(SuSE Linux)

create temp table a(keyf int, val text);
create temp table b(keyf int, val text);
create temp table c(keyf int, val text);
insert into a values(1, 'A1');
insert into a values(2, 'A2');
insert into a values(3, 'A3');
insert into a values(4, 'A4');
insert into b values(1, 'B1');
insert into b values(2, 'B2');
insert into c values(2, 'C2');
insert into b values(3, 'C3');
select keyf, a.val as aval,
coalesce(b.val,'Bxx') as bval,
coalesce(c.val,'Cxx') as cval
from a left join b using(keyf) left join c using (keyf);
keyf aval bval cval
---- ---- ---- ----
1 A1 B1 Cxx
2 A2 B2 C2
3 A3 C3 Cxx
4 A4 Bxx Cxx

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Dmitri Bichko 2005-08-17 19:38:40 Re: Locating ( FKs ) References to a Primary Key
Previous Message Roger Motorola 2005-08-17 19:06:50 Locating ( FKs ) References to a Primary Key