I have tried so many combinations so maybe I'm just simply doing it wrong. Well, I definitely am doing it wrong.
I know that code is always requested on Stack Overflow but it'll confuse the question as my code has now mutated into another language.
Confusion:
There's two WHERE
clauses and no matter where I place it, I either get an error or the JOIN
doesn't work
Problem:
I have 4 tables:
customers
- I need ALL the rows returned even if there's no payment to it but only if customer_status = 1
payments
- contains customer_id
linked to customers
table - I need the SUM returned from payment_amount
only if payment_status = 1
branches
- contains customer_id
linked to customers
table
managers
- contains branch_id
linked to branches
table
CUSTOMER | TOTAL_RECEIVED | BRANCH | MANAGER_NAME
----------------------------------------------------------------------
Pepsi | £1000 | London | Mr Smith
Coca Cola | | Manchester | Mr Beckham
Dr Pepper | £2500 | Shanghai | Mr Miagi
Duff | | Springfield | Mr Simpson
As you can see, coca cola and duff haven't paid (no record in payment table) but it should still list
- So customers should all show up if
customer_status = 1
SUM
of payment only if it's in database and payment_status = 1- Branch and Manager should list for that customer as it's always in database
- Managers is in its own table as there's many and assigned to different branches at different times (as I have a feeling someone might ask)
Fields selected and where summary
c.customer_id, c.customer_companyname, c.customer_status FROM customers c WHERE c.customer_status = 1
SUM(p.payment_amount) as total_received, p.customer_id, p.payment_status FROM payments p WHERE p.payment_status = 1
b.branch_id, b.branch, b.customer_id FROM branches b WHERE b.customer_id = c.customer_id
m.manager_id, m.manager_name, m.branch_id FROM managers m WHERE m.branch_id = b.branch_id