I have the following query:
$query = "SELECT (SELECT SUM(net_amount) FROM fin_costos WHERE month='1' AND group_of_costos='general' AND year_analysis='2014' ) +
(SELECT SUM(net_amount) FROM em2_fin_costs WHERE month='1' AND group_of_costos='general' AND year_analysis='2014') AS total";
It's basically a SUM
of 2 values retrieved from different tables. The problem appears when in one of the SELECT
statements, the record is not yet in the database and creates a NULL
, that even if the second SELECT
gets a value, creates a NULL
.
The question: How can I turn to 0 the result from the SELECT
statements if the record is not yet on the database.
Use IFNULL()
:
SELECT IFNULL((SELECT SUM(net_amount) FROM fin_costos WHERE month='1' AND group_of_costos='general' AND year_analysis='2014' ), 0) +
IFNULL((SELECT SUM(net_amount) FROM em2_fin_costs WHERE month='1' AND group_of_costos='general' AND year_analysis='2014'), 0) AS total
try This
$query = "SELECT (SELECT SUM(case when net_amount IS NOT NULL then net_amount else 0 end) FROM fin_costos WHERE month='1' AND group_of_costos='general' AND year_analysis='2014' ) + (SELECT SUM(case when net_amount IS NOT NULL then net_amount else 0 end) FROM em2_fin_costs WHERE month='1' AND group_of_costos='general' AND year_analysis='2014') AS total";