我有一个表格,其中包含如下记录:
CREATE TABLE sample (
ix int unsigned auto_increment primary key,
start_active datetime,
last_active datetime
);
Run Code Online (Sandbox Code Playgroud)
我需要知道过去30天每天有多少记录活跃.日期也应该按递增顺序进行排序,以便将它们最旧的返回到最新.
我正在使用MySQL,查询将从PHP运行,但我不需要PHP代码,只需要查询.
这是我的开始:
SELECT COUNT(1) cnt, DATE(?each of last 30 days?) adate
FROM sample
WHERE adate BETWEEN start_active AND last_active
GROUP BY adate;
Run Code Online (Sandbox Code Playgroud)
做外连接.
没有桌子?做一张桌子.我总是为此保留一张假桌子.
create table artificial_range(
id int not null primary key auto_increment,
name varchar( 20 ) null ) ;
-- or whatever your database requires for an auto increment column
insert into artificial_range( name ) values ( null )
-- create one row.
insert into artificial_range( name ) select name from artificial_range;
-- you now have two rows
insert into artificial_range( name ) select name from artificial_range;
-- you now have four rows
insert into artificial_range( name ) select name from artificial_range;
-- you now have eight rows
--etc.
insert into artificial_range( name ) select name from artificial_range;
-- you now have 1024 rows, with ids 1-1024
Run Code Online (Sandbox Code Playgroud)
现在使用方便,并将其限制为30天,并具有以下视图:
编辑:JR Lawhorne指出:
您需要将"date_add"更改为"date_sub"以在创建的视图中获取前30天.
谢谢JR!
create view each_of_the_last_30_days as
select date_sub( now(), interval (id - 1) day ) as adate
from artificial_range where id < 32;
Run Code Online (Sandbox Code Playgroud)
现在在你的查询中使用它(我实际上没有测试过你的查询,我只是假设它正常工作):
编辑:我应该加入另一种方式:
SELECT COUNT(*) cnt, b.adate
FROM each_of_the_last_30_days b
left outer join sample a
on ( b.adate BETWEEN a.start_active AND a.last_active)
GROUP BY b.adate;
Run Code Online (Sandbox Code Playgroud)