【问题标题】:Checking conditions (date, time) with MySQL使用 MySQL 检查条件(日期、时间)
【发布时间】:2012-09-14 09:14:43
【问题描述】:

我需要检查当前时间是否在数据库中的某个字段范围内。

例如,在数据库中,我将存储 start timeend timestart dateend date

然后我需要检查当前日期是否在查询返回的值范围内。

我已经尝试过:

WHERE start_date <= $currdate 
  AND end_date >= $currdate
  AND start_time <= $currtime
  AND end_time >= $currtime

这很好用,直到我们遇到日期重叠两天的情况,在这种情况下查询返回NULL,因为end_time 显然比当前时间少。

我想我需要一种方法将start_datestart_timeend_dateend_time 结合起来?

【问题讨论】:

  • 添加完整的工作查询、测试数据和预期结果,这将有助于获得您正在寻找的答案。
  • 这是您必须使用的现有数据模型,还是您正在提议?如果您有 start_datetime 和 end_datetime 列,解决这个问题将是微不足道的。

标签: mysql sql date time conditional-statements


【解决方案1】:

你试过时间戳()吗?

http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestamp

也许可以做类似的事情

WHERE timestamp(start_date, start_time) <= timestamp(currdate, currtime)
  AND timestamp(end_date, end_time) >= timestamp(currdate, currtime)

当然,这是假设您的开始/结束日期和时间是相关的。不完全确定分离这两个字段背后的业务逻辑是什么......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2020-04-16
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多