select from mysql table between datetime x min ago and datetime x min ago

后端 未结 2 751
情书的邮戳
情书的邮戳 2021-01-31 02:38

I think I summed nicely it up in the title. I want to select online users from a specific time to another specific time. My table look like this:

CREATE TABLE on         


        
相关标签:
2条回答
  • 2021-01-31 02:56

    Use DATE_SUB to subtract time from the DATETIME returned from NOW():

    last 15 minutes

    SELECT o.*
      FROM ONLINE o
     WHERE o.time >= DATE_SUB(NOW(), INTERVAL 15 MINUTE) 
    

    last 60 minutes, but not the last 15 minutes

    SELECT o.*
      FROM ONLINE o
     WHERE o.time BETWEEN DATE_SUB(NOW(), INTERVAL 60 MINUTE) 
                      AND DATE_SUB(NOW(), INTERVAL 15 MINUTE) 
    

    Duplicate handling costs extra.

    0 讨论(0)
  • 2021-01-31 03:08

    For your first query:

    SELECT username
    FROM online
    WHERE time > NOW() - INTERVAL 15 MINUTE
    

    And for your second:

    SELECT username
    FROM online
    WHERE time BETWEEN NOW() - INTERVAL 60 MINUTE AND NOW() - INTERVAL 15 MINUTE
    

    Both these queries assume that each user only appears once in the online table (and if this is indeed the case you should add a UNIQUE constraint to enforce that).

    If a username can appear more than once in the table you just need to add DISTINCT after SELECT for your first query, but you need a slightly different approach for your second query:

    SELECT DISTINCT username
    FROM online
    WHERE time > NOW() - INTERVAL 60 MINUTE
    AND NOT EXISTS
    (
        SELECT *
        FROM online
        WHERE time > NOW() - INTERVAL 15 MINUTE
    )
    
    0 讨论(0)
提交回复
热议问题