如何从数据库中每次获取7个元素

时间:2019-01-30 16:08:37

标签: mysql

在数据库中,我有评论表,为了统计,我希望每天(过去7天)获得评论总数。

我使用:

xor eax, eax
xor ebx, ebx
mov ecx, 3
loop1:
mov eax, dword[big_num1+4*(ecx-1)]
mov ebx, dword[big_num2+4*(ecx-1)]
mov [result_4word+4*(ecx-1)], eax
adc [result_4word+4*(ecx-1)], ebx
loop loop1

但是当特定日期没有评论时,它不会返回任何内容。如何填补失踪的日子?

2 个答案:

答案 0 :(得分:1)

您可以使用其他策略,而无需使用不同的表:

select 
(NOW() - INTERVAL 1 DAY) as day, (SELECT count(*) as total_comment from comments where date(created_at) = day ) as total_comments
UNION
select (NOW() - INTERVAL 2 DAY) as day, (SELECT count(*) as total_comment from comments where date(created_at) = day ) as total_comments
UNION 
select (NOW() - INTERVAL 3 DAY) as day, (SELECT count(*) as total_comment from comments where date(created_at) = day ) as total_comments
UNION
select (NOW() - INTERVAL 4 DAY) as day, (SELECT count(*) as total_comment from comments where date(created_at) = day ) as total_comments
UNION
select (NOW() - INTERVAL 5 DAY) as day, (SELECT count(*) as total_comment from comments where date(created_at) = day ) as total_comments
UNION 
select (NOW() - INTERVAL 6 DAY) as day, (SELECT count(*) as total_comment from comments where date(created_at) = day ) as total_comments
UNION 
select (NOW() - INTERVAL 7 DAY) as day, (SELECT count(*) as total_comment from comments where date(created_at) = day ) as total_comments

答案 1 :(得分:0)

这7天都需要一张桌子

select t1.day, t2. total_comments 
from (
select 1  day from dual 
union   
select 2 from dual 
union  
select 3   from dual 
union   
select 4 from dual  
union  
select 5   from dual 
union   
select 6  from dual
union 
select 7  from dual 
) t1 
left join  (
select date(created_at) as day
    , count(*) as total_comments 
from comments where DATEDIFF(NOW(), created_at) <= 7 
group by day
) t2 on t1.day = t2.day