MySQL分组多列问题

时间:2015-09-16 20:44:14

标签: mysql

我有一个包含事件的数据库表:

INSERT INTO events(device, link, down_time, up_time) VALUES('d1', 'l1', '2015-01-01 00:00:00', '2015-01-01 00:05:00');
INSERT INTO events(device, link, down_time, up_time) VALUES('d2', 'l2', '2015-01-01 00:00:01', '2015-01-01 00:00:2');
INSERT INTO events(device, link, down_time, up_time) VALUES('d2', 'l2', '2015-01-01 00:00:03', '2015-01-01 00:00:05');
INSERT INTO events(device, link, down_time, up_time) VALUES('d3', 'l3', '2015-01-01 00:00:06', '2015-01-01 00:00:09');

| device | link | down_time           | up_time             | id |
| d1     | l1   | 2015-01-01 00:00:00 | 2015-01-01 00:05:00 |  1 |
| d2     | l2   | 2015-01-01 00:00:01 | 2015-01-01 00:00:02 |  2 |
| d2     | l2   | 2015-01-01 00:00:03 | 2015-01-01 00:00:05 |  3 |
| d3     | l3   | 2015-01-01 00:00:06 | 2015-01-01 00:00:09 |  4 |

我想查找事件,及时重叠并使用以下查询:

SELECT *
FROM events a
JOIN events b
ON a.down_time <= b.up_time AND a.up_time >= b.down_time
WHERE a.link regexp 'l[12]' AND b.link regexp 'l[12]' and a.id != b.id;

这显示4行显示重叠,但是第1行和第2行显示与第3行和第4行相同的重叠事件。我想添加一个group子句进行查询,这样我只显示第1行和第2行,但无法解决问题。

| device | link | down_time           | up_time             | id | device | link | down_time           | up_time             | id |
| d2     | l2   | 2015-01-01 00:00:01 | 2015-01-01 00:00:02 |  2 | d1     | l1   | 2015-01-01 00:00:00 | 2015-01-01 00:05:00 |  1 |
| d2     | l2   | 2015-01-01 00:00:03 | 2015-01-01 00:00:05 |  3 | d1     | l1   | 2015-01-01 00:00:00 | 2015-01-01 00:05:00 |  1 |
| d1     | l1   | 2015-01-01 00:00:00 | 2015-01-01 00:05:00 |  1 | d2     | l2   | 2015-01-01 00:00:01 | 2015-01-01 00:00:02 |  2 |
| d1     | l1   | 2015-01-01 00:00:00 | 2015-01-01 00:05:00 |  1 | d2     | l2   | 2015-01-01 00:00:03 | 2015-01-01 00:00:05 |  3 |
非常感谢: - )

2 个答案:

答案 0 :(得分:1)

更改ON子句中的ID比较,以便它只选择以下两种顺序之一:

ON a.id < b.id AND a.down_time <= b.up_time AND a.up_time >= b.down_time

答案 1 :(得分:1)

您正在获得重复项,因为您的a.id != b.id允许比较两个“订单”中的行,方法是将其更改为a.id < b.id,您只能将“早期”记录与后续记录进行比较。

编辑:删除了“旁注”,我误读了重叠条件。