pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Colin Wetherbee <cww@denterprises.org>
To: Paul Lambert <plengada@optusnet.com.au>
Cc: pgsql-sql@postgresql.org
Subject: Re: JOIN a table twice for different values in the same query
Date: Thu, 10 Jan 2008 17:22:20 -0500
Message-ID: <47869A9C.7010203@denterprises.org> (raw)
In-Reply-To: <478699D0.7070608@optusnet.com.au>
References: <47869704.8050306@denterprises.org>
	<478699D0.7070608@optusnet.com.au>

Paul Lambert wrote:
> Colin Wetherbee wrote:
>> I would like to construct a query on the flight table that returns the 
>> names of both the departure port and the arrival port.
>>
>> The following query shows how I would get just the departure port.
>>
>> js=# SELECT departure_date, jsports.code AS departure_code FROM
>> jsjourneys JOIN jsports ON jsjourneys.departure_port = jsports.id LIMIT
>> 4;
>>
> Try joining twice, something like:
> 
> SELECT departure_date,
>        dp.code AS departure_code,
>        ap.code AS arrival_code
> FROM jsjourneys
> JOIN jsports dp ON jsjourneys.departure_port = jsports.id
> JOIN jsports ap ON jsjourneys.arrival_port=jsports.id
> 
> ---------------------------(end of broadcast)---------------------------
> TIP 6: explain analyze is your friend

Ah, I didn't realize you could alias tables inside the JOIN.  Excellent. 
  It works. :)

js=# SELECT departure_date, dp.code AS departure_code, ap.code AS 
arrival_code FROM jsjourneys JOIN jsports dp ON 
jsjourneys.departure_port = dp.id JOIN jsports ap ON 
jsjourneys.arrival_port = ap.id LIMIT 4;

  departure_date | departure_code | arrival_code
----------------+----------------+--------------
  2006-11-19     | BHM            | ATL
  2006-11-16     | PIT            | ATL
  2006-11-16     | ATL            | BHM
  2006-10-26     | PIT            | BOS
(4 rows)

For archive completeness, note the query is joined relative to dp.id and 
ap.id, rather than jsports.id.

Thanks for your help!

Colin



view thread (9+ messages)  latest in thread

Message-ID: <47869A9C.7010203@denterprises.org>
Permalink:  ../47869A9C.7010203@denterprises.org/
Also on:    postgresql.org/message-id/47869A9C.7010203@denterprises.org

 · 

reply

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: cww@denterprises.org, plengada@optusnet.com.au
  Subject: Re: JOIN a table twice for different values in the same query
  In-Reply-To: <47869A9C.7010203@denterprises.org>

* 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