1、需求说明
需要做个首页将系统日志前一周内的每天的日志数量显示成折线图表中:
我们需要通过sql语句查询系统表的一周前的每日数据量,查询结果的预期应该是这样的:
2、遇到问题
下面是第一个实现的版本,但是执行结果并不是我们的预期结果,因为会存在一个问题,假设系统日志在一周内的某几天没有产生数据,那么久会变成下面这个结果:
SELECT DATE_FORMAT(create_time,'%Y-%m-%d') days, COUNT(*) COUNT FROM ( SELECT * FROM sys_log WHERE DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= DATE(create_time) ) AS test GROUP BY days;
3、问题解决
首先我们需要创建一个一周内的时间虚表,然后通过left join左连接上面sql的查询结果,并注意如果为空的时候应该使用IFNULL(a.COUNT,0)去处理:
SELECT b.item,IFNULL(a.COUNT,0) AS VALUE FROM ( SELECT CURDATE() AS item UNION ALL SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY) AS item UNION ALL SELECT DATE_SUB(CURDATE(), INTERVAL 2 DAY) AS item UNION ALL SELECT DATE_SUB(CURDATE(), INTERVAL 3 DAY) AS item UNION ALL SELECT DATE_SUB(CURDATE(), INTERVAL 4 DAY) AS item UNION ALL SELECT DATE_SUB(CURDATE(), INTERVAL 5 DAY) AS item UNION ALL SELECT DATE_SUB(CURDATE(), INTERVAL 6 DAY) AS item ) b LEFT JOIN ( SELECT DATE_FORMAT(create_time,'%Y-%m-%d') days, COUNT(*) COUNT FROM (SELECT * FROM sys_log WHERE DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= DATE(create_time)) GROUP BY days ) AS a ON (b.item = a.days)
上述代码有问题可在下面评论留言哦!感谢支持!