从MySQL中选择并显示营业时间

时间:2012-11-09 22:21:56

标签: mysql

我不需要检查业务是开放还是关闭,但我需要按天显示营业时间。

有一些选择:

1 - 商业开放一天一次(样本 - 从10:00到18:30) - 一个    表中的行 2 - 商务开放时间为两天(samlpe - 从10:00到    14:00和15:00至18:30) - 表中有两行 3 - 业务可能    关闭(没有插入行)

这里我的MySql表存放时间。在此示例业务中,(affiliate_id)在0到4天内打开两次,在第5天打开一次,在第6天关闭(此时没有记录)

http://postimage.org/image/yplj4rumj/

我需要在网站上显示它(根据此数据库示例:

0,1,2,3,4 - 开放时间为10:00-14:00和15:00-18:30 5 - 营业时间为10:00-12:00 6 - 关闭

我如何得到如下结果:

http://postimage.org/image/toe53en63/

我尝试用GROUPֹ_CONCAT和LEFT JOIN在a.day = b.day上同一个表进行查询,但没有运气:(

我的查询样本(这是错误的)

SELECT GROUP_CONCAT( DISTINCT CAST( a.day AS CHAR ) 
ORDER BY a.day ) AS days, DATE_FORMAT( a.time_from,  '%H:%i' ) AS f_time_from, DATE_FORMAT( a.time_to,  '%H:%i' ) AS f_time_to, DATE_FORMAT( b.time_from, '%H:%i' ) AS f_time_from_s, DATE_FORMAT( b.time_to,  '%H:%i' ) AS f_time_to_s
FROM business_affiliate_hours AS a LEFT 
JOIN business_affiliate_hours AS b ON a.day = b.day
WHERE a.affiliate_id =57

GROUP BY a.time_from, a.time_to, b.time_from, b.time_to

 ORDER BY a.id ASC

这是我的表:

CREATE TABLE IF NOT EXISTS `business_affiliate_hours` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `affiliate_id` int(10) unsigned NOT NULL DEFAULT '0',
  `time_from` time NOT NULL,
  `time_to` time NOT NULL,
  `day` tinyint(1) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM;


INSERT INTO `business_affiliate_hours` (`id`, `affiliate_id`, `time_from`, `time_to`, `day`) VALUES
(53, 57, '10:00:00', '12:00:00', 5),
(52, 57, '15:00:00', '18:30:00', 4),
(51, 57, '10:00:00', '14:00:00', 4),
(50, 57, '15:00:00', '18:30:00', 3),
(49, 57, '10:00:00', '14:00:00', 3),
(48, 57, '15:00:00', '18:30:00', 2),
(47, 57, '10:00:00', '14:00:00', 2),
(46, 57, '15:00:00', '18:30:00', 1),
(45, 57, '10:00:00', '14:00:00', 1),
(44, 57, '15:00:00', '18:30:00', 0),
(43, 57, '10:00:00', '14:00:00', 0);

每天的营业时间可能会有所不同,所以我希望在相同的营业时间内分组,并获取所有独特的营业时间顺序的天数列表。

需要你的帮助!

很抱歉有图片的链接,我无法将图片上传到此处。

1 个答案:

答案 0 :(得分:2)

首先构建每天合并时间的物化表,然后分组:

SELECT   GROUP_CONCAT(day ORDER BY day) AS days,
         DATE_FORMAT(f1, '%H:%i') AS f_time_from,
         DATE_FORMAT(t1, '%H:%i') AS f_time_to,
         DATE_FORMAT(f2, '%H:%i') AS f_time_from_s,
         DATE_FORMAT(t2, '%H:%i') AS f_time_to_s
FROM (
  SELECT   day,
           MIN(time_from) AS f1,
           MIN(time_to  ) AS t1,
           IF(COUNT(*) > 1, MAX(time_from), NULL) AS f2,
           IF(COUNT(*) > 1, MAX(time_to  ), NULL) AS t2
  FROM     business_affiliate_hours
  WHERE    affiliate_id = 57
  GROUP BY day
) t
GROUP BY f1, t1, f2, t2
ORDER BY days

sqlfiddle上查看。