問題:mysql按日期查詢乙個月內的資料,查詢返回時結果集中只顯示有資料的結果
需求:查詢結果中假如當天沒有資料,自動填零並輸出
事件描述:
sql語句:
select date_format(date_added,"%m.%d") as day,count(product_id) as total from ht_product where date_format(date_added,"%m")=7 group by day;
返回結果:
day total
07.23 1
07.25 4
07.26 2
07.27 1
期望結果:
day total
07.01 0
07.02 0
07.22 0
07.23 1
07.24 0
07.25 4
07.26 2
07.27 1
07.28 0
07.31 0
解決方案
create table ht_product( date_added datetime, product_id int);
insert ht_product values
("2016-7-4", 11), ("2016-7-4", 33),
("2016-7-7", 11), ("2016-7-10", 33);
select _dt.day, coalesce(data.total, 0) as total
from(
select date_format(_id.date,"%m.%d") as day from(
select date_add("2016-07-01", interval @i day) as date, @i:=@i+1 as id
from information_schema.columns a, (select @i:=0) _a
order by id limit 31
) _id
where date_format(_id.date,"%m")=7
) _dt
left join(
select date_format(date_added,"%m.%d") as day,count(product_id) as total
from ht_product
where date_format(date_added,"%m")=7
group by day
) data on data.day = _dt.day
order by day
drop table ht_product;
MySQL按日期查詢資料SQL語句
查詢往前7天的資料 select from 資料表 where date sub curdate interval 7 day 你要判斷的時間欄位名查詢往前30天的資料 select from 資料表 where date sub curdate interval 30 day 你要判斷的時間欄位名...
按日期查詢
select date format create time,y u weeks,count caseid count from tc case group byweeks select date format create time,y m d days,count caseid count fr...
PHP處理,mysql按日期 時間查詢
date default timezone set prc 預設時區 echo 今天 date y m d time echo 今天 date y m d strtotime 18 june 2008 echo 昨天 date y m d strtotime 1 day echo 明天 date y...