简体   繁体   中英

Fetching rows with updated at timestamp older than 1 day in mysql

I have a table with schema as follows:

mysql> desc a;
  +---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| id            | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| created_at    | int(11)          | YES  |     | NULL    |                |
| updated_at    | int(11)          | YES  |     | NULL    |                |

In updated_at I capture timestamp.

Now I would like to fetch all rows with updated_at < NOW() - INTERVAL 1 DAY .

To do this, I have written following query taking idea from Fetching rows added last hour :

mysql> select count(*) from a where DATE(updated_at) < DATE_SUB(NOW(),INTERVAL 1 DAY);
+----------+
| count(*) |
+----------+
|        0 |
+----------+

Though there are many rows with updated at with 2 years old timestamp, I am getting 0 here.

You can't use DATE on an integer timestamp value; you must convert it to a DATE using FROM_UNIXTIME :

SELECT COUNT(*) 
FROM a
WHERE FROM_UNIXTIME(updated_at) < NOW() - INTERVAL 1 DAY

Note that you don't have to use DATE_SUB to subtract an interval, you can just write the arithmetic directly.

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