我有一张这样的表:
+--+----------+--------+-----+---+
|id|date |machine |start|end|
+--+----------+--------+-----+---+
| 1|2017-05-24|Machine1| 100|109|
| 2|2017-05-24|Machine2| 550|560|
| 3|2017-05-25|Machine1| 108|116|
| 4|2017-05-26|Machine1| 116|124|
| 5|2017-05-26|Machine2| 570|580|
+--+----------+--------+-----+---+
开始和结束字段是每台机器的小时计数器。计数器只能上升。在id为3的行中,Machine1的起始值小于id为1的行中Machine1的结束值。
有没有办法查询返回所有有错误的行?
答案 0 :(得分:0)
这将按顺序扫描所有行,并针对上一行进行检查:
SELECT
t.*,
IF(machine = @last_machine AND @last_end > `start`, @last_id, null) as wrong_pair_id,
@last_machine := machine as __t1,
@last_end := `end` as __t2,
@last_id := id as __t3
FROM (
SELECT * FROM tbl ORDER BY machine, `date`
) t
JOIN (SELECT @last_id := null, @last_end:=null, @last_machine:=null) as i
HAVING wrong_pair_id IS NOT NULL
如果要选择行对,可以将其包装在另一个SELECT中并加入wrong_pair_id