你可以做这样的事情
insert into readings (sensor_id, sensor_reading, time_of_reading)
select 42, 1234.5678, current_timestamp
from readings
where not exists (select *
from readings
where sensor_reading = 1234.5678
and time_of_reading = (select max(time_of_reading)
from readings
where sensor_id = 42);
这将需要对sensor_reading
列进行索引,但我仍然怀疑它实际上会更快。
您不需要存储haschanged
属性,因为您可以在检索数据时计算它:
select sensor_id,
sensor_reading,
time_of_reading,
lag(sensor_reading) over (partition by sensor_id order by time_of_reading) = sensor_reading as has_changed
from readings;
这假设它sensor_id
实际上并不是唯一的,否则您不能为传感器存储多个读数
它进一步假设您将该REAL
列更改为一NUMERIC
列,因为REAL
使用的值=
不准确(实际上存储开始时不准确)