[SQL] Generating a range of integers in a query

2005-07-13 Thread Aaron Bingham
Hello,

I've got an interesting problem: I need to select all possible values
of an attribute that do /not/ occur in the database.

This would be easy (in my case at least) if there were a way to
generate a table containing all integers between 1 and n, where n is
the result of a subquery.  In my case, n will be at most a few
hundred.  I would like to be able to generate this table as a
subquery.  Any ideas?

Thanks,

-- 

Aaron Bingham
Senior Software Engineer
Cenix BioScience GmbH



---(end of broadcast)---
TIP 3: Have you checked our extensive FAQ?

   http://www.postgresql.org/docs/faq


Re: [SQL] Can I do this smarter?

2006-07-14 Thread Aaron Bingham

Aaron Bono wrote:

On 7/13/06, *Joost Kraaijeveld* <[EMAIL PROTECTED] 
<mailto:[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.


You can also rewirite this (IMO) more clearly thus:

SELECT
  invoices.objectid,
  invoices.invoicenumber,
  invoices.invoicedate,
  salesorders.customer,
  customers.customernumber,
  customers.lastname
FROM invoices, salesorders, customers
WHERE salesorders.objectid = invoices.salesorderobjectid
  AND customers.objectid = salesorder.customer;

--
----
Aaron Bingham
Senior Software Engineer
Cenix BioScience GmbH



---(end of broadcast)---
TIP 3: Have you checked our extensive FAQ?

  http://www.postgresql.org/docs/faq