视图 - 如果在按查询分组中找不到行,则返回0

caa*_*os0 4 mysql view

假设我有以下MySQL视图:

create or replace view total_transactions(account_id, total) as
select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
group by t.bank_account_id;
Run Code Online (Sandbox Code Playgroud)

假设该帐户还没有任何交易,我希望该视图返回0.现在,如果我选择如下:

select * from total_transactions where account_id = 2060;
Run Code Online (Sandbox Code Playgroud)

并且帐户2060没有任何交易,它将不返回任何内容,而不是0.

我怎么能解决这个问题?

提前致谢.


编辑

我认为这可能是group by......

如果我执行我正在用于没有group by的视图的查询,它可以工作(即使没有结果也返回0),但如果我使用group by它,则为null:

select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
and account_id = 2060;
Run Code Online (Sandbox Code Playgroud)

返回0,和

create or replace view total_transactions(account_id, total) as
select
  t.account_id,
  ifnull(sum(t.value), 0) as total
from transactions t
where t.paid IS TRUE
and account_id = 2060
group by t.bank_account_id;
Run Code Online (Sandbox Code Playgroud)

返回一个空集.

Aii*_*ias 7

如果视图结果中没有条目,那么这将始终返回NULL- 这是SQL.如果你改变你SELECT对视图使用的那个,你可以实现你想要的:

SELECT IFNULL(total, 0) FROM total_transactions WHERE account_id = 2060
Run Code Online (Sandbox Code Playgroud)

编辑:

(SELECT IFNULL(total, 0) total FROM total_transactions WHERE account_id = 2060)
UNION
(SELECT 0 total)
Run Code Online (Sandbox Code Playgroud)