【问题标题】:View - Return 0 if no rows found in a grouped by query查看 - 如果在按查询分组的查询中未找到任何行,则返回 0
【发布时间】:2013-03-24 03:37:05
【问题描述】:

假设我有以下 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;

返回一个空集。

【问题讨论】:

    标签: mysql view


    【解决方案1】:

    如果视图结果中没有条目,那么这将始终返回 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)
    

    【讨论】:

    • 这很奇怪:Empty set (0,01 sec)
    • @caarlos0 - 查看我的编辑。当你得到结果和没有结果时,这应该有效。但这还不是最优雅的。
    【解决方案2】:

    在生产中,不要使用SELECT *。请参阅 this SO question 以获取有关原因的全面回复。

    所以,假设你不是,你可以使用COALESCE,它将返回第一个非空值。

    SELECT 
        COALESCE(total, 0) 
    FROM
        total_transactions
    WHERE
        account_id = '2600'
    

    【讨论】:

    • 我已经试过了:select COALESCE(total, 0) as val from total_transactions where account_id = 2060; Empty set (0,01 sec)
    • totaltotal_transactions表中的字段名还是计算结果的别名?
    • 这行不通,因为没有行,所以没有什么可以合并。
    【解决方案3】:

    对于我使用的正值

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-04
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多