简体   繁体   English

MySQL 根据 unix 纪元时间戳删除记录

[英]MySQL delete a record based on unix epoch timestamp

I have a MySQL table as follows:我有一个 MySQL 表如下:

+----------+---------------------+-----------------+---------------+
| id       | firstName           | lastName        | tstamp        |
+----------+---------------------+-----------------+---------------+
| 133      | James               | Mosher          | 1593612000000 |  
| 145      | Bill                | Turner          | 1593698400000 | 
| 146      | Jeremy              | Vine            | 1593784800000 |  
| 152      | Ramon               | Jesus           | 1593180000000 |
+----------+---------------------+-----------------+---------------+

and I wanted to be able to DELETE records based on the tstamp value (which is epoch unix time) IF they are OLDER than x days .并且我希望能够根据tstamp值(这是纪元 unix 时间)删除记录,如果它们比x days I am using the query below which should only DELETE the last row (Ramon Jesus) as it is older than 5 days ... however, it deletes ALL of the records.我正在使用下面的查询,它应该删除最后一行(Ramon Jesus),因为它超过 5 天......但是,它删除了所有记录。 Any idea what I am doing wrong?知道我做错了什么吗?

DELETE FROM students WHERE tstamp > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 5 DAY));

Your timestamps contain milliseconds which you must remove prior to the comparison, because UNIX_TIMESTAMP() returns a DATETIME value without milliseconds.您的时间戳包含在比较之前必须删除的毫秒,因为UNIX_TIMESTAMP()返回的DATETIME值没有毫秒。
Also the comparison must use the opposite inequality operator:此外,比较必须使用相反的不等式运算符:

DELETE FROM students 
WHERE tstamp / 1000 < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 5 DAY));

See the demo .演示
Results:结果:

| id  | firstName | lastName | tstamp        |
| --- | --------- | -------- | ------------- |
| 133 | James     | Mosher   | 1593612000000 |
| 145 | Bill      | Turner   | 1593698400000 |
| 146 | Jeremy    | Vine     | 1593784800000 |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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