简体   繁体   中英

MySQL select only where Timestamp is from last 10 days

I want to limit my query to results that have been entered in the last 10 days. The TIMESTAMP column is called Date. How do I do it?

$result = mysql_query("SELECT * FROM Posts WHERE (City = '$city2') ORDER by Comments DESC LIMIT 5");

Thanks

SELECT *
FROM Comments
WHERE (City = '$city2') AND (`Date` > DATE_SUB(now(), INTERVAL 10 DAY));

Note: calling a column 'Date' is poor practice, since it's a reserved word.

You can use DATEDIFF or, as already posted, DATE_SUB . Also, I suggest not using reserved words like "Date" for column names. Example for your code:

WHERE DATEDIFF(NOW(), `Date`) < 10

Try with date_sub

select * from Comments 
where City = '{$city2}' and 
`Date` > date_sub(now(), interval 10 day)

Assuming your data is hourly can also use:

(SELECT * FROM comments ORDER BY DateTime desc LIMIT 240) order by DateTime

I found this to be more exact in returning exactly 10 days to the hour.

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