我正在尝试返回在过去10秒内创建的所有行,即“date_created”< 10秒钟。这是我正在使用的sql,但这似乎不起作用:
SELECT COUNT(amount) FROM tablename WHERE date_created>= DATE_SUB(NOW(), INTERVAL 10 SECOND)
......任何人都可以帮助我吗?
非常感谢。
答案 0 :(得分:-1)
确保将date_created列设置为TIMESTAMP而不是DATETIME - 否则计算将无法正常工作。
漫长的一天。
感谢您的帮助。
答案 1 :(得分:-1)
您的查询中唯一的缺陷是它将来会返回元素:
mysql> create table tablename(
-> date_created datetime
-> );
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> insert into tablename (date_created) values
-> ('2000-02-29 15:00:00'),
-> (CURRENT_TIMESTAMP),
-> (CURRENT_TIMESTAMP - interval 5 second),
-> (CURRENT_TIMESTAMP - interval 11 second),
-> ('2022-08-14 12:00:00');
Query OK, 5 rows affected (0.01 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql>
mysql> select date_created,
-> case
-> when date_created>= DATE_SUB(NOW(), INTERVAL 10 SECOND)
-> then 'Matches'
-> else 'Does not match'
-> end as 'Match'
-> from tablename;
+---------------------+----------------+
| date_created | Match |
+---------------------+----------------+
| 2000-02-29 15:00:00 | Does not match |
| 2015-11-06 11:44:17 | Matches |
| 2015-11-06 11:44:12 | Matches |
| 2015-11-06 11:44:06 | Does not match |
| 2022-08-14 12:00:00 | Matches | <==== This is not correct
+---------------------+----------------+
5 rows in set (0.00 sec)
只需附加相应的限制:
AND date_created<=NOW()