2017-05-26 30 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