虽然我已经研究了类似的其他问题,但是无法通过跟随这些问题达成解决方案,因此发布了我的以下问题,并为了解决一个长问题而道歉,试图让我的问题更加明确。
图像显示了我的表格结构。 我想运行这样一个查询来提取3个信息,即
userId,count(),Date(viewTime)
,即用户在过去14天的间隔内每天查看的ID计数, 如果在特定日期没有用户记录,也会将计数显示为0
select userId, count(userId), Date(viewTime) from user_views
where DATE(viewTime) between DATE_SUB(DATE(NOW()), INTERVAL 90 DAY) AND now()
group by userId, date(viewTime);

通过使用上述查询,我只获得非零记录,请参见下图:
但是,我希望在没有用户交易的那些日子里将计数显示为0。我如何实现这一目标?
答案 0 :(得分:1)
您需要为此动态生成日期,然后使用左连接。另请注意,由于您正在显示user_id
,因此可能需要将不同user_id
与动态生成的日期交叉连接。
根据我以前的答案显示缺少日期MySql Single Table, Select last 7 days and include empty rows
以下是您的案例
select
t1.user_id,
coalesce(t2.cnt,0) as cnt,
t1.view_date
from
(
select DATE_FORMAT(a.Date,'%Y-%m-%d') as view_date,
x.user_id
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a,(select distinct user_id from user_views)x
where a.Date between DATE_SUB(DATE(NOW()), INTERVAL 90 DAY) AND now()
)t1
left join
(
select user_id, count(user_id) as cnt, Date(view_time) as view_time from user_views
where DATE(view_time) between DATE_SUB(DATE(NOW()), INTERVAL 90 DAY) AND now()
group by user_id, date(view_time)
)t2
on t2.view_time = t1.view_date
and t1.user_id = t2.user_id
order by t1.view_date,t1.user_id