sql - Postgresql trigger to calculate total score -


i trying learn how create trigger in postgresql. have table

thread_user - table name thread_id user_id points

thread - table name thread_id total_points

i want on update of thread_user row update total points in thread table. need select * thread_user thread_id = thread_id of inserted item , add points update thread_points in threads table. believe done in triggers maybe stored procedure better.

first step make function calculates sum of points , updates row in calculated_points table.

thereafter you'll ahve create trigger called upon inserting row in user_points table.

drop table if exists user_points cascade; create table user_points (     id          serial primary key,     user_id     int not null,     points      int not null );  drop table if exists calculated_points cascade; create table calculated_points (     id          serial primary key,     user_id     int  not null unique,     points      int not null  );  insert calculated_points (user_id, points)     values         (1, 0),         (2, 0);  create or replace function calculate_total_points()  returns trigger $calculate_total_points$ begin     update calculated_points          set points = (select sum(points)                          user_points                          user_id = new.user_id)          user_id = new.user_id;      return new; end; $calculate_total_points$ language plpgsql;  create trigger points_added   after insert   on user_points   each row   execute procedure calculate_total_points(); 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -