考虑以下两个(假设的)表
温度
* day
* time
* lake_name
* station
* temperature_f
Temperature_summary
* day
* lake_name
* station
* count_readings_over_75f
* count_readings_below_75f
如何编写 SQLite 触发器来更新insert上的temperature_summary表。我想增加点数。
谢谢你, 杰夫
答案 0 :(得分:6)
这假设您在当天插入温度之前已经创建了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;
答案 1 :(得分:0)
可以创建触发器以在单个触发器中更新计数器。这可以提高性能并将相关项目收集到一个位置。
create trigger Temperature_count_insert_trigger_lo after insert on Temperature begin
update Temperature_summary set Temperature_summary set count_readings_over_75f = count_readings_over_75f + (new.temperature_f >= 75 ), count_readings_below_75f = count_readings_below_75f + (new.temperature_f < 75)
where new.day = day and new.lake_name = lake_name and new.station = station; end;
如果可能发生更新,可能需要在温度表中包含更新的触发处理。