与MySQL合并间隔

时间:2011-12-07 15:17:34

标签: mysql merge overlapping intervals

我需要一些合并重叠间隔的帮助。

我有这张桌子:

id  start       end
1   15:30:00    16:20:00
2   10:00:00    13:00:00
3   15:00:00    16:09:00
4   11:00:00    14:00:00
5   16:20:00    16:30:00

SQL:

CREATE TABLE `intervals` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `start` time NOT NULL,
  `end` time NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `intervals` (`start`, `end`) VALUES
('15:30:00', '16:20:00'),
('10:00:00', '13:00:00'),
('15:00:00', '16:09:00'),
('11:00:00', '14:00:00'),
('16:20:00', '16:30:00');

我想要这样的输出:

id  start       end
2   10:00:00    14:00:00
3   15:00:00    16:30:00

只有开始和结束时间很重要; ID列基本上可以忽略。

PHP https://stackoverflow.com/a/4347215/1085872有类似的实现(直到第2步),但我需要只用MySQL实现合并。

1 个答案:

答案 0 :(得分:-1)

试试这个 -

SELECT MIN(i.start) start, MAX(i.end) end FROM
  (
    SELECT @a:=@a + 1 a, t1.start, GREATEST(t1.end, t2.end) AS end
    FROM (SELECT @a := 0) t, intervals t1
    JOIN intervals t2 ON t1.id <> t2.id and t1.start >= t2.start and t1.start < t2.end
  ) p
  JOIN intervals i
     ON (i.start BETWEEN p.start AND p.end) OR (i.end BETWEEN p.start AND p.end)
  GROUP BY p.a;

+----------+----------+
| start    | end      |
+----------+----------+
| 10:00:00 | 14:00:00 |
| 15:00:00 | 16:30:00 |
+----------+----------+

该查询基于此解决方案 - http://www.artfulsoftware.com/infotree/queries.php#807

根据您的数据进行测试。