1. 程式人生 > 實用技巧 >mysql leetcode 1454. 活躍使用者 連續問題, 連續出現n次

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改成你要你次數