mysql leetcode 1454. 活跃用户 连续问题, 连续出现n次
题目:
从题目可知:
求活跃用户 ———— 至少连续登录5天的人 ———— 连续区间且长度大于等于5
使用方法:
自定义变量求次数,初始次数为0,当符合条件时,次数加1
逻辑条件:
id相同,前后一行时间间隔为1天【date_sub()函数】
根据以上可以得出
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` 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改成你要你次数