gpt4 book ai didi

用于更新摘要计数的 SQLite 触发器

转载 作者:行者123 更新时间:2023-12-03 15:57:53 28 4
gpt4 key购买 nike

考虑以下两个(假设的)表

温度

* day
* time
* lake_name
* station
* temperature_f

温度_总结

* day
* lake_name
* station
* count_readings_over_75f
* count_readings_below_75f

如何编写一个 SQLite 触发器来在插入时更新 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;

关于用于更新摘要计数的 SQLite 触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2869135/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com