假设我有以下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;
假设该帐户尚未进行任何交易,我希望该视图返回0。 现在,如果我选择像:
select * from total_transactions where account_id = 2060;
账号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;
返回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;
返回一个空集。
答案 0 :(得分:7)
如果视图结果中没有条目,那么它将始终返回NULL
- 这就是SQL。如果您更改了对视图使用的SELECT
,则可以实现所需:
SELECT IFNULL(total, 0) FROM total_transactions WHERE account_id = 2060
修改强>
(SELECT IFNULL(total, 0) total FROM total_transactions WHERE account_id = 2060)
UNION
(SELECT 0 total)
答案 1 :(得分:0)
在制作中,请勿使用SELECT *
。请参阅this SO question以获取有关原因的详尽回复。
所以,假设你没有,你可以使用COALESCE
,这将返回第一个非空值。
SELECT
COALESCE(total, 0)
FROM
total_transactions
WHERE
account_id = '2600'
答案 2 :(得分:0)
对于正值,我使用
select max(x.cnt) as cnt
from (
select ifnull(meta_value, 0) as cnt from wp_postmeta where post_id = 5543 and meta_key = '_bbp_voice_count'
union
select 0 as cnt) x
或任何
select x.cnt
from (
select ifnull(meta_value, 0) as cnt from wp_postmeta where post_id = 5543 and meta_key = '_bbp_voice_count'
union
select 0 as cnt
) x
limit 1