a LEFT JOIN problem - Mailing list pgsql-general

From Thomas
Subject a LEFT JOIN problem
Date
Msg-id 55da14450810251411i1fb5896dtd17379317f6bb095@mail.gmail.com
Whole thread Raw
Responses Re: a LEFT JOIN problem  ("Tony Wasson" <ajwasson@gmail.com>)
List pgsql-general
Hi,

I have the following tables:

Product(id, title, price)
Item(id, product_id, order_id, quantity)
Order(id, user_id, amount, paid)
User(id, name)

What I want to achieve is a query on a specific Product based in its
title. If the product has at least 1 order in which it appears, then
return the Product and Order details, if the product has no paid order
associated, then only return the Product fields.

I have tried the following query:
--
SELECT products.*, paid FROM "products"
LEFT OUTER JOIN items ON products.id = items.product_id
LEFT OUTER JOIN orders ON items.order_id = orders.id
LEFT OUTER JOIN users ON orders.user_id = users.id
WHERE (title = E'some-product' AND paid = 1 AND name = 'thomas')
--

The problem with my query, is that if there are no paid associated
orders, then the WHERE will drop every returned line that has paid =
0, therefore I don't get anything at all, but I would like to have at
least the products field.

Moreover, the "name" argument in the WHERE comes from the user logged
in data. So if the user is not logged in, no fields are returned.

Is that possible to achieve in only one query? What is the correct way
of doing it?

pgsql-general by date:

Previous
From:
Date:
Subject: Re: JDBC - Call stored function that returns user defined type
Next
From: "Tony Wasson"
Date:
Subject: Re: a LEFT JOIN problem