使用触发器计算SQLite中行之间的差异
给定如下表结构:使用触发器计算SQLite中行之间的差异,sql,sqlite,triggers,Sql,Sqlite,Triggers,给定如下表结构: update structure set new.diff = new.measurement - (select s.measurement from structure s where date < new.date order by
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;
ID |测量|差异|日期
其中ID和Date是复合主键,行由Date列进一步索引
我想在insert或replace into之后使用触发器来计算表的Diff列。Diff列只记录相同ID的两个相邻日期之间测量值的差异
在SQLite中这样做的最佳方式是什么?性能在这里至关重要,因为表很大,即超过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;
更新应该使用主键索引来快速识别行。子查询应使用日期索引快速查找上一行。因此,这应该具有合理的性能。谢谢您的回答。在选择上一个日期的度量值的子查询部分,我们可以在那里为id指定一个条件,而不是在update语句级别指定吗?如果是的话,我想知道在表现上是否有什么不同。这是我自己的理解。谢谢。@skyork。您可以指定您喜欢的任何条件。对于上述示例,出于性能原因,建议使用日期索引。