Joe
Joe

Reputation: 675

Postgresql trigger to calculate total score

I am trying to learn how to create a trigger in postgresql. I have a table

Thread_user - table name

thread_id user_id points

Thread - table name

thread_id total_points

I want to on update of any thread_user row to update the total points in the thread table. I need to basically select * from thread_user where thread_id = <thread_id of inserted item> and then add the points then update thread_points in the threads table. I believe this is done in triggers but maybe a stored procedure would be better.

Upvotes: 1

Views: 5220

Answers (1)

Cyberlurk
Cyberlurk

Reputation: 764

First step is to make a function which calculates the sum of points and updates a row in the calculated_points table.

Thereafter you'll have to create a trigger which is called upon inserting a row in the 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 INTO calculated_points (user_id, points)
    VALUES
        (1, 0),
        (2, 0);

CREATE OR REPLACE FUNCTION calculate_total_points() 
RETURNS trigger AS $calculate_total_points$
BEGIN
    UPDATE calculated_points 
        SET points = (SELECT SUM(points)
                         FROM user_points
                         WHERE user_id = NEW.user_id)
         WHERE user_id = NEW.user_id;

    RETURN NEW;
END;
$calculate_total_points$ LANGUAGE plpgsql;

CREATE TRIGGER points_added
  AFTER INSERT
  ON user_points
  FOR EACH ROW
  EXECUTE PROCEDURE calculate_total_points();

Upvotes: 3

Related Questions