SQL and DateTime - How do I select all rows that have existed for a specific time period?
I have a table with a row named time
of type DATETIME
.
How can I select all rows which 'live' no more than 5 days?
Or in other words, how can I grab data which has timestamp开发者_JAVA技巧 not more then 5 days ago?
My request:
SELECT *
FROM `stats`
WHERE `domain` = 'test.com' AND DATEADD(NOW(), interval -5 day) > 'accept_date'
accept_date
is the real name of a row. So , with that code I got:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') > 'accept_date' LIMIT 0, 30' at line 1
It depends on the RDBMS but in MySQL it would be
where date_add(now(), interval -5 day) > time
or
where datediff(now(), time) < 5
The first means "120 hours have passed since", the second means "5 calendar days have passed since".
time
is a terrible column name, by the way. Time of what?
'accept_date'
is not the name of a column - it's a character literal.
You want
AND DATE_ADD(NOW(), interval -5 day) > accept_date
(note the missing single quotes '
around the column name)
GETDATE() is DB specific, yet:
select * from TABLE where (GETDATE() - time) <= 5
精彩评论