Check for x consecutive days - given timestamps in database

后端 未结 4 1517
情深已故
情深已故 2020-11-27 16:32

Could anybody give me an idea or hint how you could check for X consecutive days in a database table (MySQL) where logins (user id, timestamp) are stored?

Stackoverf

4条回答
  •  春和景丽
    2020-11-27 17:30

    That's a hard problem to solve with SQL alone.

    The core of the problem is that you need to compare dynamic results sets to each other in one query. For example, you need to get all the logins/session IDs for one DATE, then JOIN or UNION them with a list to a grouping of logins from the DATE() (which you could use DATE_ADD to determine). You could do this for N number of consecutive dates. If you have any rows left, then those sessions have been logged in over that period.

    Assume the following table:

    sessionid int, created date

    This query returns all the sessionids that have have rows for the last two days:

    select t1.sessionid from logins t1 
      join logins t2 on t1.sessionid=t2.sessionid 
      where t1.created = DATE(date_sub(now(), interval 2 day)) 
        AND t2.created = DATE(date_sub(now(), interval 1 day));
    

    As you can see, the SQL will get gnarly for 30 days. Have a script generate it. :-D

    This further assumes that every day, the login table is updated with the session.

    I don't know if this actually solves your problem, but I hope I have helped frame the problem.

    Good luck.

提交回复
热议问题