寻找下一次业务开放; mysql小时计算

时间:2012-10-27 13:46:32

标签: php mysql sql select

我正在试图找出一家商店目前是否在营业时间内,如果没有,请在下次营业时选择。

最后,我需要能够将开幕日作为具体日期。

有人可以给我一个如何构建此查询的提示吗?

提前致谢

CREATE TABLE `shop_hours` (
  `id` int(11) NOT NULL,
  `shop_id` int(11) unsigned NOT NULL,
  `day_of_week` int(11) unsigned NOT NULL,
  `open_time` time NOT NULL,
  `close_time` time NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `shop_hours` (`id`, `shop_id`, `day_of_week`, `open_time`, `close_time`)
VALUES
    (1, 1, 0, '08:00:00', '24:00:00'),
    (2, 1, 1, '08:00:00', '24:00:00'),
    (3, 1, 2, '08:00:00', '24:00:00'),
    (4, 1, 3, '08:00:00', '24:00:00'),
    (5, 1, 4, '08:00:00', '24:00:00'),
    (6, 1, 5, '08:00:00', '24:00:00'),
    (7, 1, 6, '08:00:00', '24:00:00');

修改

为了澄清一点,我不打算找到开放的商店,但只有一个特定商店的营业时间。根据开盘/收盘时间,以及现在的时间。我将生成一些可选的时间戳,增加15分钟。

E.g。如果一家商店刚刚关闭(下午1点),我将需要使用下一个开放日的开放/关闭时间。 (商店不一定每天营业,周日可能会关闭。)

2 个答案:

答案 0 :(得分:3)

要查找shop_id,NOW()

即可开启
SELECT *
  FROM `shop_hours`
 WHERE `day_of_week` = DATE_FORMAT(NOW(), '%w')
   AND CURTIME() BETWEEN `open_time` AND `close_time`

过时

要查找明天的可用open_time s:

SELECT *
  FROM `shop_hours`
 WHERE `day_of_week` = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 1 DAY), '%w')

修改 2:

查找下一个可用的open_time

  SELECT `shop_id`,
         MIN(CAST(CONCAT(DATE(DATE_ADD(NOW(), INTERVAL ((7 + DATE_FORMAT(NOW(), '%w') - `day_of_week`) % 7) DAY)), ' ', `open_time`) AS DATETIME)) AS `next_open_datetime`
    FROM `shop_hours`
GROUP BY `shop_id`

修改

DATE_FORMAT(*DATE*, '%w')使用格式0 = Sunday ... 6 = Saturday

如果要在1 = Monday ... 7 = Sunday字段中使用ISO格式day_of_week,则应将php的date('N')绑定到查询(或使用Mysql的if函数IF(DATE_FORMAT(NOW(), '%w') = 0, 7, DATE_FORMAT(NOW(), '%w')),但那太丑了)

答案 1 :(得分:2)

1)检查商店是否开放。如果商店关闭,结果为空:

select * from shop_hours
where shop_id = $id
      and dayofweek(curdate()) = day_of_week
      and curtime() between open_time and close_time;

2)找到下一个开放时间:

(select open_time from shop_hours
 where shop_id = $id and curtime() < open_time
       and day_of_week >= dayofweek(curdate()))
union
(select open_time from shop_hours
 where shop_id = $id and curtime() < open_time
 order by day_of_week)
 union
(select open_time from shop_hours
 where shop_id = $id and curtime() > close_time
       and day_of_week >= dayofweek(curdate()))
union
(select open_time from shop_hours
 where shop_id = $id and curtime() > close_time
 order by day_of_week)
limit 1;

未经测试,但此 应该尊重周末的周转时间(即关闭日期)。

请注意,dayofweek()数字1 =星期日,2 =星期一,...如果您的表格以不同的格式存储工作日,则必须相应地调整查询。