2017-05-26 35 views
-1

我有这样的一个表:发现场的错误记录,只能改变向上

+--+----------+--------+-----+---+ 
|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

SELECT x。* FROM my_table x JOIN my_table y ON y.first_thing与x.first_thing相同并且y.second_thing比x.second_thing更大AND y.third_thing比x.third_thing更小 – Strawberry

+0

您可以发布'show CREATE table table_name;'? – RomanPerekhrest

回答

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

+0

'@last_id:= id,因为__t3应该在@last_end之后?' –

+0

是的,我错过了那个 – Vatev