![](/img/trans.png)
[英]Query to return (grouped) rows where no row with column=condition exists
[英]View - Return 0 if no rows found in a grouped by query
假设我有以下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;
返回一个空集。
如果视图结果中没有条目,那么这将始终返回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)
对于我使用的正值
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.