【问题标题】:how to check time comparsion in mysql如何在mysql中检查时间比较
【发布时间】:2016-09-06 10:58:28
【问题描述】:

我想检查当前时间是否在给定的两次之间,使用下面的 mysql 查询,

id start_time end_time
1  08:00 PM   08:00 AM

select *,if((serverTime >= startTime and serverTime <= endTime),'MetTheTime','DintMetTheTime') as Status  from( select STR_TO_DATE(concat(SUBSTRING_INDEX(start_time, ' ', 1),':00 ',SUBSTRING_INDEX(start_time, ' ', -1)),'%l:%i:%S %p') as startTime,STR_TO_DATE(concat(SUBSTRING_INDEX(end_time, ' ', 1),':00 ',SUBSTRING_INDEX(end_time, ' ', -1)),'%l:%i:%S %p') as endTime,time(now()) as serverTime from( select start_time,end_time from table  where id=1) a) b;

当我执行查询输出是:

startTime  endTime   serverTime  Status
20:00:00   08:00:00  03:47:57    DintMetTheTime

但预期的输出是:

startTime  endTime   serverTime  Status
20:00:00   08:00:00  03:47:57    MetTheTime

我哪里做错了?

基于回答帖子。我输入了Time

select *,if((serverTime >= startTime and serverTime <= endTime),'MetTheTime','DintMetTheTime') as Status  from( select start_time as startTime, end_time as endTime,time(now()) as serverTime from( select start_time,end_time from table  where id=1) a) b;

但是那个条件还是不行?

【问题讨论】:

  • 确保表格中的字段类型为time
  • 但我不应该保留字段类型是时间。必须是字符串。
  • 然后尝试在您的查询中使用STR_TO_DATE(startTime , "%h:%i:%s") 而不是startTime 并与其他人相同然后比较时间
  • 我试过了。但结果还是一样。
  • @PunitGajjar 即使我尝试输入时间。但这种情况仍然不起作用。

标签: mysql datetime time


【解决方案1】:

看起来你没有足够的逻辑来解释过夜。在您的示例serverTime &gt;= startTime 中,您可以看到'03:47:57' &gt;= '20:00:00' 是假的,不是真的。

您需要制定一些特殊用途的逻辑,以便在结束时间值小于开始时间值的情况下使用;表示隔夜的时间间隔。

【讨论】:

    【解决方案2】:

    非常简单的解决方案只需将表格的列数据类型更改为datetime 而不是time 并存储日期和时间,现在它应该可以正确计算

    【讨论】:

    • 我应该将时间存储为 08:00 PM 而不是 08:00:00。
    • 不是强制性的,因为您可以将字符串转换为时间戳。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    相关资源
    最近更新 更多