mysql sum() two joined tables, multiplies result
i have two tables; invoices & invoiceitems.
invoiceitems contains the items on each invoice
eg:
invoices
----------------------------------
| id |status| net | tax | total |
----------------------------------
| 72 |paid | 100 | 120 | 220 |
| 73 |unpaid| 50 | 5 | 55 |
| 74 |paid | 400 | 45 | 445 |
| 75 |paid | 250 | 67 | 317 |
invoiceitems
-------------------------------
| invoiceid |itemdescription |
-------------------------------
| 72 | apples |
| 72 | pears |
| 72 | oranges |
| 73 | lemons |
| 73 | oranges |
as you can see, in the example invoice number 72 has 3 items
i want to search my invoices for certain things, and display a count of
certain fields.
but my problem is that the sum value seems to get multiplied by the number
of fields there are in the second table.
$sql = "SELECT COUNT(DISTINCT invoices.id) AS num,
SUM(CASE invoices.status WHEN 'Paid' THEN 1 ELSE 0 END) AS numpaid,
SUM(CASE invoices.status WHEN 'Paid' THEN invoices.total ELSE 0 END) AS
sumtotal,
FROM invoices
LEFT JOIN invoiceitems ON invoices.id=invoiceitems.invoiceid
WHERE invoices.id LIKE :invoiceid
AND IFNULL(opcinvoiceitems.itemdescription, '') LIKE :itemdescription
AND invoices.net LIKE :net
AND invoices.tax LIKE :tax
AND invoices.total LIKE :total
AND ......"
so using the above, the total for invoice 72 would be multiplied by 3
i'm really sorry, i know this is really badly explained but i cant explain
it any other way, been searching for ages but cant find a solution. hope
someone can help. thanks
No comments:
Post a Comment