简体   繁体   中英

MySQL WHERE condition to select all records from start of the hour

WHERE timestamp >= NOW() - INTERVAL 1 HOUR

The above query works fine to get data that belongs to last 1 HOUR. Let's say I run the query at 2020-10-15 18:08:00. It will give me all the records between the below time period.

2020-10-15 17:08:00 - 2020-10-15 18:08:00

I have been trying to create a mysql query to get data from the beginning of the hour. Let's again say I ran the query at 2020-10-15 18:08:00. I need a query to get me the results belonging the below time period.

2020-10-15 18:00:00 - 2020-10-15 18:08:00

I would appreciate some feedback on this.

In many databases (as Postgres for example), you can do this with date_trunc() , or the-like (in Oracle: trunc() ).

Unfortunately MySQL does not implement this function - however it is flexible enough to understand dates as strings. I like to use date_format for this:

where timestamp >= date_format(now(), '%Y-%m-%d %H:00:00')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM