how do i get mysql results of todays date?

醉酒当歌 提交于 2019-12-11 13:31:54

问题


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...


回答1:


You can extract the date part of the timestamp field and compare it against the current date.

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



回答2:


"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.




回答3:


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.




回答4:


I tend to use TO_DAYS() to turn times into a day number, e.g.

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



回答5:


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.



来源:https://stackoverflow.com/questions/1427061/how-do-i-get-mysql-results-of-todays-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!