mysql優(yōu)化 - mysql 查7天數(shù)據(jù),無數(shù)據(jù)的補(bǔ)0怎么寫呢?
問題描述
表里有個(gè)字段紀(jì)錄每次點(diǎn)擊的時(shí)間,查最近7天每日的數(shù)據(jù),但其中可能有幾天沒數(shù)據(jù),怎么把沒數(shù)據(jù)的天數(shù)設(shè)置為0,sql語句怎么寫
問題解答
回答1:據(jù)我所知,mysql只能說在null的時(shí)候返回其他值(比如SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123) , 0);),但像題主這樣要補(bǔ)上本來不存在的數(shù)據(jù)挺難,可能別人會(huì)有方法。
我想說的是,就算sql能搞定這件事,也最好不要放sql,而是放在你的應(yīng)用程序里。這種邏輯性的東西放程序里更好管控,也更方便理解
回答2:先構(gòu)建一個(gè)最近7天的結(jié)果集,然后和查詢出的結(jié)果集做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
