I'm trying to make this query work:
SELECT
IFNULL(SUM(days), 0) AS days
FROM
`table_days`
WHERE task = 1
GROUP BY task
UNION
ALL
SELECT
IFNULL(SUM(total), 0) AS total
FROM
`table_total`
WHERE task = 1
GROUP BY task ;
I have two tables :
1. table_days
id task days
==========================
1 1 3.00
2 1 2.00
2. table_total
id task total
==========================
1 3 0.00
The query above partially works, the result is:
stdClass Object
(
[days] => 5.00
)
but I would like to get the result from second table even if there are no records found. Something like
stdClass Object
(
[days] => 5.00
[total] => 0.00
)
This code will work for you (example at sqlfiddle):
SELECT
IFNULL(SUM(days), 0) AS value, 'days' as name
FROM
`table_days`
WHERE task = 1
GROUP BY task
UNION ALL
(SELECT CASE WHEN u.value = -1 then 0 else value end as value, 'total' as name
FROM
(
SELECT
IFNULL(SUM(total), 0) AS value
FROM
`table_total`
WHERE task = 1
GROUP BY task
UNION
SELECT -1 as value
) u
);
And it will return:
+-------+-------+
| value | name |
+-------+-------+
| 5 | days |
| 0 | total |
+-------+-------+
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments