在MySQL中存储时间范围并确定当前时间是否在时间范围内

时间:2011-06-04 16:20:17

标签: php mysql sql codeigniter time

我有一个数据库表,以TIME格式存储商店的营业时间作为时间范围。例如,如果商店的营业时间是'上午9点至下午5点',那么将有2列'hours_open'和'hours_close',我在'hours_open'中存储9:00,在'hours_close'中存储17:00。要确定商店当前是打开还是关闭,我将运行查询:

SELECT * 
  FROM shop 
 WHERE CAST(NOW() AS TIME) BETWEEN hours_open AND hours_close;

我现在需要做的是容纳营业时间超过午夜的商店,如晚上9点至凌晨3点。此外,商店在不同的日子可以有不同的开放时间,例如:周一至周四:晚上9点至凌晨3点,周五至周日:晚上9点至凌晨5点。

现在我很难过。我该怎么办?我每天可以有一对'hours_open'和'hours_close',例如:'mon_hours_open','mon_hours_close','tue_hours_open','tue_hours_close'......

但是,如何处理午夜过夜时间的开放时间,如下午9点至凌晨5点?

任何见解?如果有帮助,我正在使用PHP和Codeigniter框架。

4 个答案:

答案 0 :(得分:3)

如果将它们存储在单独的表格中,则会更容易检查小时数,例如

shop_working_hours (
  shop_id int FK,
  day_of_week int,
  hours_open time,
  hours close time,
  PK (shop_id, day_of_week)
)

这样查询可能是这样的:

SELECT s.*
FROM shop s
  INNER JOIN shop_working_hours h ON s.id = h.shop_id
WHERE
  CASE
    WHEN h.hours_close > h.hours_open THEN
      h.day_of_week = DAYOFWEEK(NOW()) AND
      CAST(NOW() AS time) >= h.hours_open AND CAST(NOW() AS time) < h.hours_close
    ELSE
      h.day_of_week = DAYOFWEEK(NOW() - 1) AND
      CAST(NOW() AS time) >= h.hours_open OR CAST(NOW() AS time) < h.hours_close
  END

但是,如果您希望在同一个表中每周的每一天都有多个列,例如*_hours_open*_hours_close,即shop表,那么过滤条件很可能必须更复杂,也许是这样的:

SELECT s.*
FROM shop s
  CROSS JOIN (
    SELECT 1 AS day_of_week
    UNION ALL SELECT 2
    UNION ALL SELECT 3
    UNION ALL SELECT 4
    UNION ALL SELECT 5
    UNION ALL SELECT 6
    UNION ALL SELECT 7
  ) h
WHERE
  CASE h.day_of_week
    WHEN 1 THEN
      CASE
        WHEN s.mon_hours_close > s.mon_hours_open THEN
          h.day_of_week = DAYOFWEEK(NOW()) AND
          CAST(NOW() AS time) >= s.mon_hours_open AND
          CAST(NOW() AS time) < s.mon_hours_close
        ELSE
          h.day_of_week = DAYOFWEEK(NOW() - INTERVAL 1 DAY) AND
          CAST(NOW() AS time) >= s.mon_hours_open OR
          CAST(NOW() AS time) < s.mon_hours_close
      END
    WHEN 2 THEN
      CASE
        WHEN s.tue_hours_close > s.tue_hours_open THEN
        …  /* same for Tuesday */
      END
    …  /* and for all the other days of week */
  END

答案 1 :(得分:1)

这样的日子,你的商店桌上有两个条目,一个是周一09:00:00 - 11:59:59,另一个是周二12:00:00 - 03:00:00?

答案 2 :(得分:1)

您的opening表格中可以有三个字段:

opening
    day_opens       <--- what day the shop opens
    hour_opens      <--- what hour the shop opens
    duration_open   <--- how many hours it stays open

如果它现在打开(或在某个特定日期和时间),那么它就是这样的条件:

WHERE (   day_opens = Day(NOW()) 
      AND hourOpens <= Hour(NOW())
      AND Hour(NOW()) < hourOpens + duration_open 
      )
   OR (   day_opens + 1 = Day(NOW())
      AND Hour(NOW()) < hourOpens + duration_open - 24
      )

甚至在一种情况下更好:

WHERE day_opens * 24 + hourOpens    <= Day(NOW()) * 24 + Hour(NOW())
  AND Day(NOW()) * 24 + Hour(NOW()) <  day_opens * 24 + hourOpens + hourOpens

答案 3 :(得分:0)

有很好的想法:给定的预订期限是否可用? (http://www.artfulsoftware.com/infotree/queries.php#576)。 它在类似的情况下帮助了我。