Re: multiple lookup per row

From: "Josh Berkus" <josh(at)agliodbs(dot)com>
To: 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 14:41:22
Message-ID: web-88697@davinci.ethosmedia.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Gary,

First: Go out and buy "SQL for Smarties". Now. Read it.

However, I'll give you this one as a freebie:

> I've got a table 'phones' which has an indexed key 'pid' of type
> int4, and a
> phone number of type varchar(12).
>
> I've then got a table 'members' which as an index key 'mid' of type
> int4.

SELECT members.mid, members.name, members.address, hp.phone AS
home_phone, wp.phone AS work_phone, cp.phone as cell_phone
FROM members LEFT OUTER JOIN
(SELECT mid, phone FROM phones WHERE ptype = 'home') hp
ON members.mid = hp.mid
LEFT OUTER JOIN
(SELECT mid, phone FROM phones WHERE ptype = 'work') wp
ON members.mid = wp.mid
LEFT OUTER JOIN
(SELECT mid, phone FROM phones WHERE ptype = 'cell') cp
ON members.mid = cp.mid
ORDER BY members.name;

You're experiencing the usual problem encountered by procedural
programmers when they first start on SQL. SQL is a declarative
language, and requires a different knid of thinking than procedural
languages. Thus the use of table aliasing and subselects above.

Have fun!

-Josh

______AGLIO DATABASE SOLUTIONS___________________________
Josh Berkus
Complete information technology josh(at)agliodbs(dot)com
and data management solutions (415) 565-7293
for law firms, small businesses fax 621-2533
and non-profit organizations. San Francisco

Attachment Content-Type Size
unknown_filename text/plain 2 bytes
unknown_filename text/plain 2 bytes
unknown_filename text/plain 2 bytes

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Josh Berkus 2001-07-20 14:47:31 Re: Records exactly the same.
Previous Message Bruce Momjian 2001-07-20 14:22:59 Re: pl/pgsql - code review + question