从2个重叠日期时间范围中获取小时数

时间:2017-05-13 06:44:04

标签: php mysql

我想确定如何从2个重叠的日期时间范围中获取时间。例如,使用下表:

    CREATE TABLE IF NOT EXISTS `schedules` (
      `id` int(11) unsigned NOT NULL auto_increment,
      `start1` datetime NOT NULL,
      `end1` datetime NOT NULL,
      `start2` datetime NOT NULL,
      `end2` datetime NOT NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=37;



    INSERT INTO `schedules` (`id`, `start1`, `end1`, `start2`, `end2`) VALUES
        (1, '2017-04-16T14:00:00', '2017-04-16T23:00:00', '2017-04-16T22:00:00', '2017-04-17T06:00:00'),
        (2, '2017-04-17T17:00:00', '2017-04-18T02:00:00', '2017-04-17T22:00:00', '2017-04-18T06:00:00'),
        (3, '2017-04-18T15:00:00', '2017-04-19T01:00:00', '2017-04-18T22:00:00', '2017-04-19T06:00:00')
        (4, '2017-04-19T22:00:00', '2017-04-20T06:00:00', '2017-04-19T22:00:00', '2017-04-20T06:00:00'),
        (5, '2017-04-20T23:00:00', '2017-04-21T08:00:00', '2017-04-20T22:00:00', '2017-04-21T06:00:00');

结果应该是:

   id, Hours
    1,   1
    2,   4
    3,   3
    4,   8
    5,   7

我以前使用过多个IF语句,但我觉得它运行缓慢。如果您能给我一个简单快速的查询,我将非常高兴。

2 个答案:

答案 0 :(得分:0)

我认为它在end1和start2之间存在差异。

如果有,请尝试使用timedifftime_to_sec

select id, time_to_sec(timediff(end1, start2)) / 3600 from schedules;

Demo

答案 1 :(得分:0)

是的,你说I previously got a way using multiple IF statement,这个解决方案看起来很像,但无论如何,试试看,可能会更好吗?

select `schedules`.*, 
CASE 
    WHEN `end2` <=  `start1` OR `start2` >= `end1` THEN  NULL -- not overlaps at all
    WHEN `start2` <= `start1` AND `end2` <= `end1` THEN  TIMESTAMPDIFF(HOUR, `start1`, `end2`)  
    WHEN `start2` <= `start1` AND `end2` > `end1`  THEN  TIMESTAMPDIFF(HOUR, `start1`, `end1`)
    WHEN `start2` > `start1` AND `end2` <= `end1`  THEN  TIMESTAMPDIFF(HOUR, `start2`, `end2`)
    WHEN `start2` > `start1` AND `end2` > `end1`   THEN  TIMESTAMPDIFF(HOUR, `start2`, `end1`)
END AS hourdiff
from `schedules`