为了让事情变得更简单,只需将今天访问过的所有人都找出来,然后查找过去7天内的访问记录,如果找到一个,则返回最近的访问日期。我认为这种方法更容易理解。
select b.`hash` ,
audience.last_visit
from behaviour b
inner join (select v.`hash`, max(v.timestamp) as last_visit from audience v
where DATE(v.timestamp) between date_sub(current_date, interval 7 day) and
date_sub(current_date, interval 1 day)
group by v.`hash`) as audience
on(b.`hash` = audience.`hash`)
where DATE(b.timestamp) = CURDATE();
我们加入的选择已经包含了我们需要的信息(最近7天内每个哈希的最新访问记录)。
返回的行数是今天和过去一周访问您页面的访客数量。
您还可以从您的选择中计算得出您要查询的数量作为查询结果。
select count(*) from
(select b.`hash` ,
audience.last_visit
from behaviour b
inner join (select v.`hash`, max(v.timestamp) as last_visit from audience v
where DATE(v.timestamp) between date_sub(current_date, interval 7 day) and
date_sub(current_date, interval 1 day)
group by v.`hash`) as audience
on(b.`hash` = audience.`hash`)
where DATE(b.timestamp) = CURDATE() ) as my_visitors;
- 测试数据
drop table if exists your_schema.behaviour;
create table your_schema.behaviour(`hash` varchar(255), `timestamp` timestamp) ;
insert into your_schema.behaviour
values ('ab','2016-05-23'),('ac','2016-05-23');
drop table if exists your_schema.audience;
create table your_schema.audience (`hash` varchar(255), `timestamp` timestamp) ;
insert into your_schema.audience
values ('ab','2016-05-01'),('ab','2016-05-02'),('ab','2016-05-03'),('ab','2016-05-04'),('ab','2016-05-21'),('ab','2016-05-23'),
('ac','2016-05-01'),('ac','2016-05-02'),('ac','2016-05-03'),('ac','2016-05-04'),('ac','2016-05-21'),('ac','2016-05-23'),
('ad','2016-05-01'), ('ad','2016-05-02'), ('ad','2016-05-03'),('ad','2016-05-04'),('ad','2016-05-21'),('ad','2016-05-23');
audience
=首次访问列表,behaviour
=这些用户的页面访问?那么您的group by views
将采用注册/首次访问的日期(因此不会区分访问日期)-您可能只需要在distinct
中添加b.timestamp
即可。但请添加缺失的信息,这样我们就不必猜测了。 - Solarflare