Re: Can I do this smarter? - Mailing list pgsql-sql

From Aaron Bono
Subject Re: Can I do this smarter?
Date
Msg-id [email protected]
Whole thread Raw
In response to Can I do this smarter?  (Joost Kraaijeveld <[email protected]>)
Responses Re: Can I do this smarter?
Re: Can I do this smarter?
List pgsql-sql
On 7/13/06, Joost Kraaijeveld <[email protected]> wrote:
I have three tables: customers, salesorders and invoices. Customers have
salesorders and salesorders have invoices ( child tables have foreign
key columns to their parent).

I want to get a list of all invoices with their customers. This what I
came up with:

select
invoices.objectid,
invoices.invoicenumber,
invoices.invoicedate,
(select customer from salesorders where objectid = invoices.salesorderobjectid),
(select customernumber from customers where objectid = (select customer from salesorders where objectid = invoices.salesorderobjectid)),
(select lastname from customers where objectid = (select customer from salesorders where objectid = invoices.salesorderobjectid))
from invoices

Can I do this smarter as the three subselects select the same customer three times and I would think that 1 time is enough?

 
SELECT
   invoices.objectid,
   invoices.invoicenumber,
   invoices.invoicedate,
   salesorders.customer,
   customers.customernumber,
   customers.lastname
FROM invoices
INNER JOIN salesorders ON (
   salesorders.objectid = invoices.salesorderobjectid
)
INNER JOIN customers ON (
   customers.objectid = salesorder.customer
)

You should do INNER and OUTER  joins for connecting the tables by their foreign keys.

==================================================================
   Aaron Bono
   Aranya Software Technologies, Inc.
   http://www.aranya.com
==================================================================

pgsql-sql by date:

Previous
From: Joost Kraaijeveld
Date:
Subject: Can I do this smarter?
Next
From: Joost Kraaijeveld
Date:
Subject: Re: Can I do this smarter?