Date Range Query MySQL

有些话、适合烂在心里 提交于 2019-11-29 08:42:57

You can use the now timedate function in MySQL and the BETWEEN operator.

Raw SQL:

SELECT * FROM news
WHERE NOW() BETWEEN start AND end;

Note: Be mindful of the default timezone, which affects the NOW() function, used by the server providing your MySQL resource.

You have >= in both conditions.

You can use the mysql function curdate() to get the date as 2010-01-05, or now() to get the full datetime format 2010-01-05 12:55:09. It depends if you want to find items that start today or start right now.

And assuming you don't have any entries that end before they begin you could rewrite the query as

select * from news where start = curdate()

It's probably a good idea to double-check your end dates too. And it seems that you're looking for a list of news articles that have already started but not yet ended, so the query looks like this

select * from news where start < now() and end > now()

You should even be able to do this, although I haven't tested it

select * from news where now() between start and end

Your mileage may vary.

--Mark

This works for me. select * from news where start between '$range1' and '$range2'

Tegan Snyder

Thank everyone I ended up using:

select * 
from news 
where start = curdate()

I tried

SELECT * 
FROM news 
WHERE NOW() BETWEEN start AND end;

and it worked almost correctly. It didn't want to show news articles that both started and ended on the same day at the same time.

-tegan

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