How to efficiently determine changes between rows using SQL

前端 未结 2 1560
鱼传尺愫
鱼传尺愫 2021-01-05 18:27

I have a very large MySQL table containing data read from a number of sensors. Essentially, there\'s a time stamp and a value column. I\'ll omit the sensor id, indexes other

2条回答
  •  伪装坚强ぢ
    2021-01-05 19:04

    You might try this - I'm not going to guarantee that it will perform better, but it's my usual way of correlating a row with a "previous" row:

    SELECT
        * --TODO, list columns
    FROM
        data d
           left join
        data d_prev
           on
               d_prev.time < d.time --TODO - Other key columns?
           left join
        data d_inter
           on
               d_inter.time < d.time and
               d_prev.time < d_inter.time --TODO - Other key columns?
    WHERE
        d_inter.time is null AND
        (d_prev.value is null OR d_prev.value <> d.value)
    

    (I think this is right - could do with some sample data to validate it).

    Basically, the idea is to join the table to itself, and for each row (in d), find candidate rows (in d_prev) for the "previous" row. Then do a further join, to try to find a row (in d_inter) that exists between the current row (in d) and the candidate row (in d_prev). If we cannot find such a row (d_inter.time is null), then that candidate was indeed the previous row.

提交回复
热议问题