当前位置:Gxlcms > 数据库问题 > mysql leetcode 1454. 活跃用户 连续问题, 连续出现n次

mysql leetcode 1454. 活跃用户 连续问题, 连续出现n次

时间:2021-07-01 10:21:17 帮助过:21人阅读

id, @cnt:=if(@id=id and @pre_date=date_sub(login_date, interval 1 day), @cnt+1, 1) as cnt, @id:=id, @pre_date:=login_date from (select * from `Logins` order by id, login_date) as a (select @id:=null, @pre_date:=null, @cnt:=0) as b

 

注意!!!有坑
由题目或者一般情况下,用户一天内登录次数可能不止一次,所以会有同用户同时间多次的登录记录存在
所以得去

select
id,
@cnt:=if(@id=id and @pre_date=date_sub(login_date, interval 1 day), @cnt+1, 1) as cnt,
@id:=id,
@pre_date:=login_date
from 
(select * from `Logins` group by id, login_date order by id, login_date) as a
(select @id:=null, @pre_date:=null, @cnt:=0) as b

以上是第一步
第二步与用户信息表连接,以次数超过5为条件,使用distinct去重
根据题目要求,还需要排序

select
distinct a1.id, a1.name
from `Accounts` as a1
inner join (
    select
    id,
    @cnt:=if(@id=id and @pre_date=date_sub(login_date, interval 1 day), @cnt+1, 1) as cnt,
    @id:=id,
    @pre_date:=login_date
    from
    (select * from `Logins` group by id, login_date order by id, login_date) as a,
    (select @id:=null, @pre_date:=null, @cnt:=0) as b
) as b1
on a1.id = b1.id
where b1.cnt >= 5
order by a1.id

求n次,那就将5改成你要你次数

mysql leetcode 1454. 活跃用户 连续问题, 连续出现n次

标签:sub   com   info   相同   mda   数加   container   rom   使用   

人气教程排行