MySQL查询根据unix时间戳范围是否出现在本月返回行?
我有一个像这样的记录集,其中包含 unix 时间戳 来记录日期:
+----+-----------+-----------+---------+
|Id |Start Date |EndDate |MoreData |
+----+-----------+-----------+---------+
|1 |1292692439 |2147483647 |... |
+----+-----------+-----------+---------+
|2 |1272776400 |1274331600 |... |
+----+-----------+-----------+---------+
|3 |1293256800 |2147483647 |... |
+----+-----------+-----------+---------+
|4 |1294552800 |2147483647 |... |
+----+-----------+-----------+---------+
我需要做的是编写一个 MySQL 查询(使用 PHP),该查询仅返回包含 或 中的开始日期的行本月之前并且结束日期在本月或之后。
例如,在上面的记录集中,如果查询本月(2010 年 12 月),则不应返回 id 为 2 和 4 的行,因为 2 的结束日期是 2010 年 5 月,4 的开始日期是 2011 年 1 月。
帮助了解如何查询可能看起来非常感谢,或者在编写此查询时,有关 MySQL 查询命令的任何想法可能会很有用?
I have a record-set like this that contains unix timestamps to record dates:
+----+-----------+-----------+---------+
|Id |Start Date |EndDate |MoreData |
+----+-----------+-----------+---------+
|1 |1292692439 |2147483647 |... |
+----+-----------+-----------+---------+
|2 |1272776400 |1274331600 |... |
+----+-----------+-----------+---------+
|3 |1293256800 |2147483647 |... |
+----+-----------+-----------+---------+
|4 |1294552800 |2147483647 |... |
+----+-----------+-----------+---------+
What i need to do is write a MySQL query (using PHP) that only returns the rows that contain the startdate that is in or before this month and the enddate is in or after this month.
For example, in the above record-set, if querying for this month (December 2010) the rows with id 2 and 4 should not be returned because 2's enddate is in May 2010 and 4's startdate is in January 2011.
Help with how the query might look is greatly appreciated or any ideas with what MySQL query commands might come in useful when writing this query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该可以解决问题:
This should do the trick:
由于您需要从 PHP 启动查询,明智的做法是在 PHP 中计算给定月份的第一天和最后一天的时间戳,并将这些值作为参数提供给 MySQL 查询。您需要这样的东西:
然后您可以不带参数调用此函数来获取当前月份的所有记录,或者您可以传递任何日期字符串(可以由 strtotime() 解析)来获取特定月份的记录。
Since you need to initiate your query from PHP, the sensible thing is to calculate the timestamps for first and last day of the given month in PHP, and feed these values as parameters to your MySQL query. You'd need something like this:
And then you can call this function without parameter to get all records for the current month, or you can pass any date string - that can be parsed by strtotime() - to get records for a specific month.
我实际上使用这种格式来测试日期:
这是最容易实现的。这是 Thrustmaster 在评论中建议的。
I actually used this format to test dates:
Which was the easiest and most simple to implement. It was suggested by Thrustmaster in the comments.