简体   繁体   中英

Create triggers for calculating sum in postgres

I have this tables in postgres

CREATE TABLE voting_option (
  id SERIAL PRIMARY KEY,
  -- SUM of all vote values for this voting option id
  votes_value INT NOT NULL DEFAULT 0
);
CREATE TABLE vote (
  id SERIAL PRIMARY KEY,
  voting_option_id INT NOT NULL,
  -- can be positive/negative or 0
  value INT NOT NULL
);

I want to create triggers that will automatically update votes_value every time I INSERT / UPDATE / DELETE a record to the vote table.

Something like this:

For INSERT: votes_value += vote.value

For DELETE: votes_value -= vote.value

For UPDATE: votes_value = votes_value - old vote.value + new vote.value

As @JimJones noticed, all you need is this simple view. You will have clean insert-only workflow as a bonus too instead of an update workflow in disguise.

create view voting_option_v as
 select voting_option_id id, sum(value) votes_value
 from vote 
 group by voting_option_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM