考虑以下两个(假设的)表
温度
* day * time * lake_name * station * temperature_f
Temperature_summary
* day * lake_name * station * count_readings_over_75f * count_readings_below_75f
如何编写SQLite Trigger来更新insert上的temperature_summary表.我想增加点数.
谢谢,杰夫
假设您在当天插入温度之前已经创建了day/lake_name/station的记录.当然,你可以添加另一个触发器来做到这一点.
create trigger Temperature_count_insert_trigger_hi after insert on Temperature when new.temperature_f >= 75 begin update Temperature_summary set count_readings_over_75f = count_readings_over_75f + 1 where new.day = day and new.lake_name = lake_name and new.station = station; end; create trigger Temperature_count_insert_trigger_lo after insert on Temperature when new.temperature_f < 75 begin update Temperature_summary set count_readings_below_75f = count_readings_below_75f + 1 where new.day = day and new.lake_name = lake_name and new.station = station; end;
您可以将这些组合成一个稍微复杂的触发器
create trigger Temperature_count_insert_trigger after insert on Temperature begin update Temperature_summary set count_readings_below_75f = count_readings_below_75f + (new.temperature_f < 75), count_readings_over_75f = count_readings_over_75f + (new.temperature_f >= 75) where new.day = day and new.lake_name = lake_name and new.station = station; end;
要确保Temperature_summary中有一行要更新(a)在Temperature_summary上创建一个唯一索引(day, lake_name, station)
,或者将这些列作为主键,并且(b)在触发器中执行插入或忽略,如下所示:
create trigger Temperature_count_insert_trigger after insert on Temperature begin insert or ignore into Temperature_summary values (new.day, new.lake_name, new.station, 0, 0); update Temperature_summary set count_readings_below_75f = count_readings_below_75f + (new.temperature_f < 75), count_readings_over_75f = count_readings_over_75f + (new.temperature_f >= 75) where new.day = day and new.lake_name = lake_name and new.station = station; end;