当前位置:  开发笔记 > 数据库 > 正文

SQLite触发器更新摘要计数

如何解决《SQLite触发器更新摘要计数》经验,为你挑选了1个好方法。

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

温度

* 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表.我想增加点数.

谢谢,杰夫



1> Doug Currie..:

假设您在当天插入温度之前已经创建了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;

推荐阅读
有风吹过best
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有