Count rows in mysql database where timestamp within X interval

后端 未结 2 1385
北荒
北荒 2021-01-20 00:59

I am trying to count the rows in a table in my database that were inserted within X hours or X days. I have tried repeatedly but I keep getting empty set responses.

相关标签:
2条回答
  • 2021-01-20 01:30

    Rather than selecting rows where start_stamp is equal to now() - 1day, you need rows where it is greater than or equal to that range. Additionally, your syntax is a little off. MySQL's date arithmetic uses column_value - INTERVAL <number> <period>, so you need:

    SELECT COUNT(*) AS num_new_rows
    FROM mytable
    WHERE start_stamp >= NOW() - INTERVAL 1 DAY
    

    Likewise to get n hours ago, use INTERVAL n HOUR

    # Within 3 hours...
    WHERE start_stamp >= NOW() - INTERVAL 3 HOUR
    

    The syntax for date interval arithmetic is described in a small paragraph beneath the DATE_ADD() function reference in the official MySQL documentation.

    0 讨论(0)
  • 2021-01-20 01:43

    Here are a some examples...

    All entries within the past 6 hours:

    select * from mytable where start_stamp >= now() - interval 6 hour;
    

    All entries within the past 2 days:

    select * from mytable where start_stamp >= now() - interval 2 day;
    

    All entries within the past 2 1/2 days:

    select * from mytable where start_stamp >= now() - interval 2 day - interval 12 hour;
    
    0 讨论(0)
提交回复
热议问题