当提现表没有数据[Account No: 100.200.330.444]
且存款表没有数据[Account No: 100.200.330.444]
时,则仅显示NULL
。
但我想显示0
。
我创建虚拟表
并制作main balance
[Account No: 100.200.330.444]
我的代码,例如deposit_amount - withdraw_amount = Result
撤回表为空时,然后反馈null
我想显示main_balance = 0
CREATE VIEW xyz as select account_no as account_no,
CASE
when sum(deposit_amount)=null then 0
when sum(deposit_amount)=0 then 0
ELSE sum(deposit_amount)
END
-
(select
CASE
when sum(withdraw_amount)=null then 0
when sum(withdraw_amount)=0 then 0
ELSE sum(withdraw_amount)
END
from withdraws
)as balance from deposits group by account_no
答案 0 :(得分:1)
我认为您应该以{{1}}的形式编写此查询:
JOIN
请注意,我假设每个帐户至少都有一笔存款(用于开设该帐户)。否则,您将需要模拟FULL JOIN(有关方法,请参见this question)。
答案 1 :(得分:0)
不能在Null字段上使用算术运算符。空为Unknown
,因此x = unknown
始终是未知的。
如果要检查为空,则可以使用
IsNull: i.e. IsNull(Field)
is null: i.e. Where Field is null;
coalesce: i.e. coalesce(Field, valueIfNull)
答案 2 :(得分:0)
由于MySQL对视图的限制,几乎不可能在MySQL视图中准确表达。如果要使用所有帐户,请从帐户表开始,并在select
中使用相关子查询:
select a.account_no,
((select coalesce(sum(d.deposit_amount), 0)
from deposits d
where d.account_no = a.account_no
) -
(select coalesce(sum(d.withdraw_amount), 0)
from withdraws w
where w.account_no = a.account_no
)
) as balance
from accounts a;
MySQL不允许FROM
子句中的子查询,这使其他表达方式更具挑战性。