SQL 中没有条目时返回 0

Returning 0 when there are no entries in SQL

我正在尝试填充图表,但是,如果没有条目,则不会打印任何内容。当什么都不存在时,它应该 return 为“0”。

我试过对我的 COUNT 使用 IFNULL,但这没有任何区别。

SQL:

SELECT DATE_FORMAT(date(created_at), "%d. %b") AS date, IFNULL(count(*), 0) as count 
FROM users
WHERE created_at BETWEEN NOW() - INTERVAL 14 DAY AND NOW()
Group by date
ORDER BY date(created_at) ASC

我了解到您想填写范围内缺失的日期。

一个选项是首先生成整个期间的一系列日期,然后将 table 与 left join 相结合,然后进行汇总。同样,一个选项使用递归查询,在 MySQL 8.0:

中可用
with recursive dates as (
    select current_date - interval 14 day dt
    union all
    select dt + interval 1 day from dates where dt < current_date
)
select date_format(d.dt, '%d. %b'), count(u.created_at) cnt
from dates d
left join users u 
    on  u.created_at >= d.dt
    and u.created_at <  d.dt + interval 1 day
group by d.dt, date_format(d.dt, '%d. %b')
order by d.dt