问题背景
很多系统都有这样的程序流程,如下:
前端页面选择时间->后端接收到日期范围数据如(startDate=20190303,endDate=20190401)->查询MYSQL
->后端返回数据到前端->前端加载数据渲染曲线
但是有时候因为业务本身或者系统异常等原因会导致某些日期无数据,如上假设20190303天无数,那么前端渲染曲线就会缺失某个点,容易误导用户。
方案解决
后端获取到日期范围数据(startDate=20190303,endDate=20190401),先生成该范围连续无断点的时间数据.
如
select * from(
select '20190303' time_str
UNION ALL
select '20190304' time_str
...
UNION ALL
select '20190401' time_str ) a
把该数据命名为a表。
然后把a表left join 到 select time_str,count(*) num from table group by time_str的统计数据。
join后 num 结果如果为NULL的话,我们把它设置为0,如语句case when num is null then 0 else num end 。
最后的sql语句结构如下
select a.time_str,
case when b.num is null then 0 else b.num end
from(
select '20190303' time_str
UNION ALL
select '20190304' time_str
...
UNION ALL
select '20190401' time_str ) a
left join (
select time_str,count(*) num from table group by time_str
)b on a.time_str=b.time_str