Count rows in mysql database where timestamp within X interval

后端 未结 2 1402
北荒
北荒 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条回答
  •  萌比男神i
    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 , 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.

提交回复
热议问题