简体   繁体   中英

how do i get mysql results of todays date?

I'm trying to pull results from a table that have been inserted today. Each insert is marked with a timestamp.

If I do a query like:

SELECT * 
  FROM table 
  WHERE added > DATE_SUB(NOW(), INTERVAL 1 DAY) 

It seems I get stuff that did fall on today's date, but also stuff from 24 hours ago. maybe I'm seeing things.

I don't want to see stuff from 24 hours ago...

您可以提取时间戳字段的日期部分 ,并将其与当前日期进行比较。

SELECT x,y,z FROM t WHERE Date(added)=Curdate()

you can use the trick that mysql compares a date as being at midnight when compared to a datetime value:

SELECT * FROM table WHERE added >= CURRENT_DATE

this has the advantage that it can use an index.

"interval 1 day" does not mean "the same calendar day", it means "within 24 hours". There are many situations where this is useful. Like, you might want to say, Show me all the responses to my posts made within the last 24 hours. If I ran such a query when I arrived at work in the morning, it would tell me all the responses that came in since I asked yesterday morning, plus those that came in this morning before I arrived. That would likely be what I want to know.

Apparently it's not useful in your case, so ... use something else! Like the other posters have suggested.

I tend to use TO_DAYS() to turn times into a day number, eg

SELECT * 
  FROM table 
  WHERE TO_DAYS(added)=TO_DAYS(NOW())
SELECT * 
FROM table 
WHERE DATE(added) = DATE(NOW()) 

DATE(added) will remove the hours, minutes and seconds from your date, if they're there.

NOW() returns today's date and time.

DATE(NOW()) returns today's date.

So if you do WHERE DATE(added) = DATE(NOW()) then you will only get results where the date is today's date.

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