mysql sum error
Today I was fighting with strange error.
SELECT
-- ...
(
(SELECT SUM(t.v)
FROM tab1 t
)
+
(SELECT SUM(t.v)
FROM tab2 t
)
) AS x
-- ...
Something like that give me NULL in x in every row even if there was a lot of records in tab1. Here is why: If no rows match then SUM return NULL, not 0. And another bad think is NULL + 1 = NULL. So to correct that I need to do like this:
SELECT
-- ...
(
IFNULL((
SELECT SUM(t.v)
FROM tab1 t
),0)
+
IFNULL((
SELECT SUM(t.v)
FROM tab2 t
),0)
) AS x
-- ...
Now it work. I hope it will help you.