SELECT IF{
(select sum(amount)
from bank_credit
where bank_name='IDBI') -
(select sum(amount)
from bank_debit
where bank_name='IDBI') as idbi == NULL}
else {
select sum(amount)
from bank_credit
where bank_name='IDBI')
} as idbi
如何用mysql中的if else解决这个子查询... plz帮助一些
答案 0 :(得分:0)
您可以使用function ifnull()
将NULL
转换为0
,然后进行计算。
SELECT
IFNULL(
( SELECT SUM(amount)
FROM bank_credit
WHERE bank_name='IDBI'
), 0
)
-
IFNULL(
(
SELECT SUM(amount)
FROM bank_debit
WHERE bank_name='IDBI'
), 0
) AS idbi;
另见https://stackoverflow.com/a/1441358/1331451。
使用此查询查看isnull()
的行为:
select
ifnull( (select 1), 0) - ifnull( (select 1), 0) as 1_1,
ifnull( (select 1), 0) - ifnull( (select 0), 0) as 1_0,
ifnull( (select 1), 0) - ifnull( (select NULL), 0) as 1_NULL,
ifnull( (select 0), 0) - ifnull( (select 1), 0) as 0_1,
ifnull( (select NULL), 0) - ifnull( (select 1), 0) as NULL_1,
ifnull( (select NULL), 0) - ifnull( (select NULL), 0) as NULL_NULL
;