IFNULL
will come handy here:
SELECT t1.uid, SUM(t1.item) - IFNULL(SUM(t2.item), 0)
FROM table1 t1 LEFT JOIN table2 t2 ON t1.uid = t2.uid
GROUP BY t1.uid
It replaces NULL's with the appropriate values, here it is 0.
Frage
I have two tables:
table 1: stock
uid|item|
--------
01 |value1
02 |value2
02 |value2
etc|etc
table 2: sales
uid|item
--------
02|value2
02|value2
02|value2
How do I get the difference between stock (sum of one item) - total sales (sum) of a product? I have tried to calculate the difference between two sums but sometimes I subtract "nothing" from stock, because maybe an item is not present in the sales table and I get something like:
2 - NULL = NULL and I want something like 2-0 = 2
Lösung 2
IFNULL
will come handy here:
SELECT t1.uid, SUM(t1.item) - IFNULL(SUM(t2.item), 0)
FROM table1 t1 LEFT JOIN table2 t2 ON t1.uid = t2.uid
GROUP BY t1.uid
It replaces NULL's with the appropriate values, here it is 0.
Andere Tipps
MySQL does not implement a MINUS operation - which is a unfortunate as it can allow for better execution plans in some cases than the alternatives:
SELECT a.*
FROM a
LEFT JOIN b
ON a.id=b.id
WHERE b.id IS NULL
or...
SELECT a.*
FROM a
WHERE a.id NOT IN (
SELECT b.id
FROM b
)
sum(ifnull(item,0)) - sum(ifnull(product,0))