From: Tom Lane <tgl@sss.pgh.pa.us>
To: Josh Berkus <josh@agliodbs.com>
Cc: Gary Stainburn <gary.stainburn@ringways.co.uk>
Cc: pgsql-sql <pgsql-sql@postgresql.org>
Subject: Re: multiple lookup per row
Date: Fri, 20 Jul 2001 11:47:47 -0400
Message-ID: <3691.995644067@sss.pgh.pa.us> (raw)
In-Reply-To: <web-88697@davinci.ethosmedia.com>
References: <web-88697@davinci.ethosmedia.com>
"Josh Berkus" <josh@agliodbs.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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: tgl@sss.pgh.pa.us, josh@agliodbs.com, gary.stainburn@ringways.co.uk
Subject: Re: multiple lookup per row
In-Reply-To: <3691.995644067@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox