mysql 选择 30 天范围内的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12098899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:35:41  来源:igfitidea点击:

mysql select dates in 30-day range

mysqldate

提问by sys_debug

This must be simple but I fiddled with it, and didn't get anything I wanted. I have the following code:

这一定很简单,但我摆弄了它,并没有得到我想要的任何东西。我有以下代码:

SELECT id,title,start_date 
  FROM events 
 WHERE start_date > DATE_SUB(NOW(), INTERVAL 1 MONTH) 
  AND city = '$cityName' 
ORDER BY start_date DESC

Now this selects events with dates in this month, but the definition of this month shown in query is different than what I need. I need it to show me events within 30 days and not only this month i.e. august. If I insert an event in august it shows the outcome. If I do insert september, it doesn't even though it is less than 30 days away.

现在这选择了本月日期的事件,但查询中显示的本月定义与我需要的不同。我需要它在 30 天内向我展示事件,而不仅仅是这个月,即 8 月。如果我在八月插入一个事件,它会显示结果。如果我在 9 月插入,即使距离不到 30 天也不会插入。

回答by Mark Byers

You should change 1 MONTHto 30 DAY:

你应该1 MONTH改为30 DAY

WHERE start_date > NOW() - INTERVAL 30 DAY

To limit it to 30 days in either direction:

要在任一方向将其限制为 30 天:

WHERE start_date > NOW() - INTERVAL 30 DAY
AND start_date < NOW() + INTERVAL 30 DAY

回答by Scott Presnell

How about like this:

像这样怎么样:

...WHERE DATE(start_date) BETWEEN DATE_SUB(NOW(),INTERVAL 30 DAY) and DATE_SUB(NOW(),INTERVAL 1 DAY) AND city...

回答by d4c0d312

OR

或者

AND TIMESTAMPDIFF(DAY,YOURDATE,now()) < 30

AND TIMESTAMPDIFF(DAY,YOURDATE,now()) < 30

This gives you a 30 day span

这为您提供了 30 天的跨度

回答by Humphrey

I hope this will help also

我希望这也会有所帮助

SELECT id,title,start_date 
  FROM events 
 WHERE  city = "$cityName" AND 
TIMESTAMPDIFF(DAY,start_date,now()) < 30   
ORDER BY start_date DESC