使用触发器计算 SQLite 中行之间的差异

Use trigger to calculate difference between rows in SQLite

给定这样的 table 结构:

ID|Measurement|Diff|Date

其中 IDDate 是复合主键,行由 Date 列进一步索引。

我想使用触发器(在 insert or replace into 之后)计算 table 的 Diff 列。 Diff 列只是记录了相同 ID.

的两个相邻日期之间的 Measurement 值的差异

在 SQLite 中执行此操作的最佳方法是什么?性能在这里至关重要,因为 table 很大,即 1M+ 行。

计算值的查询应该是这样的:

update structure
    set new.diff = new.measurement - (select s.measurement
                                      from structure s
                                      where date < new.date
                                      order by date desc
                                      limit 1)
    where id = new.id;

update 应该使用主键索引来快速识别行。子查询应该使用 date 索引来快速找到上一行。所以,这应该有合理的表现。