MySQL 日期范围查询
我需要一个查询来选择两个日期之间的数据,并以今天的日期作为参考。
该数据库具有“开始”的日期时间字段和“结束”的日期时间字段。
$todays_date = date("Y-m-d H:i:s");
$q = "SELECT * FROM news WHERE `end` >= '" . $todays_date . "' AND `start` >= '" . $todays_date . "' ORDER BY id DESC";
问题是查询仍在提取开始日期大于今天的结果。然后我将查询修改为如下所示:
$q = "SELECT * FROM news WHERE `end` >= '" . $todays_date . "' AND `start` >= '" . $todays_date . "' AND `start` <='" . $todays_date . "' ORDER BY id DESC";
这是在使用今天的日期作为限制器的两个日期时间字段之间选择数据的正确方法吗?
谢谢
I need a query to select data between two dates with today's date as a reference.
The database has a datetime field for "start" and a datetime field for "end".
$todays_date = date("Y-m-d H:i:s");
$q = "SELECT * FROM news WHERE `end` >= '" . $todays_date . "' AND `start` >= '" . $todays_date . "' ORDER BY id DESC";
The problem is the query is still pulling results where the start date is greater than today. So then i modified my query to look like this:
$q = "SELECT * FROM news WHERE `end` >= '" . $todays_date . "' AND `start` >= '" . $todays_date . "' AND `start` <='" . $todays_date . "' ORDER BY id DESC";
Is this the correct way of selection data between two datetime fields that uses todays date as a limiter?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 MySQL 中的 now timedate 函数和 BETWEEN< /a> 运算符。
原始 SQL:
注意:请注意默认时区,它会影响提供 MySQL 资源的服务器所使用的 NOW() 函数。
You can use the now timedate function in MySQL and the BETWEEN operator.
Raw SQL:
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.
您可以使用 mysql 函数 curdate() 获取日期为 2010-01-05,或 now() 获取完整的日期时间格式 2010-01-05 12:55:09。这取决于您想要查找从今天开始还是从现在开始的项目。
假设您没有任何在开始之前结束的条目,您可以重写查询,因为
仔细检查结束日期可能也是个好主意。看起来您正在寻找已经开始但尚未结束的新闻文章列表,因此查询看起来像这样
您甚至应该能够执行此操作,尽管我还没有测试它
您的里程可能会有所不同。
- 标记
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
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
You should even be able to do this, although I haven't tested it
Your mileage may vary.
--Mark
这对我有用。
从“$range1”和“$range2”之间开始的新闻中选择 *
This works for me.
select * from news where start between '$range1' and '$range2'
感谢我最终使用的每个人:
我尝试过
,它几乎可以正常工作。它不想显示在同一天同时开始和结束的新闻文章。
-特根
Thank everyone I ended up using:
I tried
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