[英]Return counts of 0 from mysql “count()”
I have the below query running on mysql 我在mysql上运行以下查询
SELECT DATE(field) AS day, COUNT( * ) AS totalSessions
FROM table
GROUP BY DATE(field)
ORDER BY field DESC
LIMIT 7
It returns 它回来了
day | totalSessions
2013-12-17 | 5
2013-12-15 | 1
What would I need to change on my query so that I would get the results 我需要更改我的查询以便获得结果
day | totalSessions
2013-12-17 | 5
2013-12-16 | 0
2013-12-15 | 1
2013-12-14 | 0
2013-12-13 | 0
2013-12-12 | 0
2013-12-11 | 0
You may need to store (somewhere) the dates you want to return. 您可能需要存储(某处)要返回的日期。 I think a stored procedure can help you: 我认为存储过程可以帮助您:
delimiter $$
create procedure getStuff(d0 date, d1 date)
begin
declare d date;
drop table if exists temp_dates;
create temporary table temp_dates (
d date not null primary key
);
set d = d0;
while d <= d1 do
insert into temp_dates values (d);
set d = date_add(d, interval +1 day);
end while;
select
a.d as day,
count(b.field) as totalSessions
from
temp_dates as a
left join yourTable as b on a.d = b.dateField -- Assuming "dateField" holds the date
group by
a.d;
end $$
delimiter ;
Hope this helps 希望这可以帮助
Not the best looking solution but worth a shot: 不是最好看的解决方案,但值得一试:
SELECT
FAKE.dt,
COUNT(YT.id) AS totalSessions
FROM (
SELECT DATE(NOW()) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 2 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 3 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 4 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 5 DAY)) as dt
UNION SELECT DATE(DATE_SUB(NOW(), INTERVAL 6 DAY)) as dt
) FAKE
LEFT JOIN yourtable YT ON YT.datefield = FAKE.dt
GROUP BY FAKE.dt
ORDER BY FAKE.dt DESC
So you select 7 dates backwards starting today, union the results, left join the data you need, group and order by date. 因此,您从今天开始向后选择7个日期,结合结果,左键加入您需要的数据,按日期分组和排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.