mysql优化 - mysql 查7天数据,无数据的补0怎么写呢?
问题描述
表里有个字段纪录每次点击的时间,查最近7天每日的数据,但其中可能有几天没数据,怎么把没数据的天数设置为0,sql语句怎么写
问题解答
回答1:据我所知,mysql只能说在null的时候返回其他值(比如SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123) , 0);),但像题主这样要补上本来不存在的数据挺难,可能别人会有方法。
我想说的是,就算sql能搞定这件事,也最好不要放sql,而是放在你的应用程序里。这种逻辑性的东西放程序里更好管控,也更方便理解
回答2:先构建一个最近7天的结果集,然后和查询出的结果集做Left Join,如:
select a.click_date, ifnull(b.click_qty, 0)from ( select * from ( SELECT curdate() as click_date union all SELECT date_sub(curdate(), interval 1 day) as click_date union all SELECT date_sub(curdate(), interval 2 day) as click_date union all SELECT date_sub(curdate(), interval 3 day) as click_date union all SELECT date_sub(curdate(), interval 4 day) as click_date union all SELECT date_sub(curdate(), interval 5 day) as click_date union all SELECT date_sub(curdate(), interval 6 day) as click_date )) a left join ( select click_date, count(*) as click_qty from click_log_table group by click_date) b