Re: multiple lookup per row

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Josh Berkus" <josh(at)agliodbs(dot)com>
Cc: Gary Stainburn <gary(dot)stainburn(at)ringways(dot)co(dot)uk>, "pgsql-sql" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: multiple lookup per row
Date: 2001-07-20 15:47:47
Message-ID: 3691.995644067@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"Josh Berkus" <josh(at)agliodbs(dot)com> writes:
> ... LEFT OUTER JOIN ...

Another way is correlated subselects in the output list:

SELECT mid, name, address,
(SELECT phone FROM phones
WHERE members.mid = phones.mid and ptype = 'home') AS home_phone,
(SELECT phone FROM phones
WHERE members.mid = phones.mid and ptype = 'work') AS work_phone,
(SELECT phone FROM phones
WHERE members.mid = phones.mid and ptype = 'cell') AS cell_phone
FROM members;

With either of these approaches, you'll get NULLs for cases where the
member has no phone number of the given type. However, what you ought
to think about is what happens if the member has more than one phone
number of a single type. With the outer join you will get multiple
output rows for that member, which is likely not what you want. With
my way, you'd get an execution error, which is definitely not what you
want... but you could patch it by including LIMIT 1 in the sub-SELECTs,
and perhaps also an ORDER BY to determine *which* phone number is the
single one shown.

BTW, I second Josh' recommendation of "SQL for Smarties".

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Tom Lane 2001-07-20 15:58:25 Re: Cast '' (blank) to null date
Previous Message Chris Ruprecht 2001-07-20 15:21:04 TODO List