I have a table of customers, orders, and items. I’d like to write a report with one customer per row (for this example I’m assuming one order per customer) and whether certain items were ordered.
customers:
id firstName
orders:
id customers_id
items:
id orders_id
I’m having problems displaying a row if a particular item has not been ordered (e.g. apples)
What I’d like is a report with 3 columns:
- First Name
- Apples
- Bananas
Here is the query I’m using:
SELECT c.firstName, i_apple, i_banana
FROM customers
LEFT JOIN orders o ON c.id = o.customers_id
LEFT JOIN items i_apple ON o.id = i_apple.orders_id
LEFT JOIN items i_banana ON o.id = i_banana.orders_id
WHERE i_apple = 'apple' AND i_banana = 'banana'
Everything is fine, but you need to filter outer joins in ON clause of the join, otherwise you turn outer into an inner join. I’ve added
Namecolumn to Items but it should probably beProductID, a foreign key to Product table with ProductName.