I have two table:
// posts
+----+---------+-----------+-------------+
| id | title | content | total_votes |
+----+---------+-----------+-------------+
| 1 | title1 | content1 | 3 |
| 2 | title2 | content2 | 2 |
+----+---------+-----------+-------------+
// votes
+----+---------+-------+
| id | id_post | value |
+----+---------+-------+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 1 | 1 |
| 4 | 2 | -1 |
| 5 | 2 | 1 |
| 6 | 2 | 1 |
| 7 | 2 | 1 |
+----+---------+-------+
Now I need to a trigger for updating posts.total_votes
. when one user gives a new vote (1 or -1), It will be a new row in votes
table, SO I want to after inserting in to votes
table, automatically trigger updates the number of total_votes
and apply new vote. Is it possible ?
For example:
If new votes.values == 1 then posts.totla_votes++;
If new votes.values == -1 then posts.total_votes--;
EDIT:
I have two posts table (posts_A | posts_B). Also I add a new column on the votes table contained the name of tables. So I need to the trigger updates appropriate table. something like this: update new.table_name ...
instead of update posts ...
.
// posts_A
+----+---------+-----------+-------------+
| id | title | content | total_votes |
+----+---------+-----------+-------------+
| 1 | title1 | content1 | 2 |
| 2 | title2 | content2 | -1 |
+----+---------+-----------+-------------+
// posts_B
+----+---------+-----------+-------------+
| id | title | content | total_votes |
+----+---------+-----------+-------------+
| 1 | title1 | content1 | 1 |
| 2 | title2 | content2 | 3 |
+----+---------+-----------+-------------+
// votes
+----+---------+-------+------------+
| id | id_post | value | table_name |
+----+---------+-------+------------+
| 1 | 1 | 1 | post_A |
| 2 | 1 | 1 | post_A |
| 3 | 1 | 1 | post_B |
| 4 | 2 | -1 | post_A |
| 5 | 2 | 1 | post_B |
| 6 | 2 | 1 | post_B |
| 7 | 2 | 1 | post_B |
+----+---------+-------+------------+
Here is my try, But I don't know why it does not work? :
delimiter //
create trigger total_votes_count_upd after update on votes
for each row
begin
if (new.value == 1) then
update new.table_name set total_votes = total_votes+1
where id = new.id_post;
elseif (new.value == -1) then
update new.table_name set total_votes = total_votes-1
where id = new.id_post;
end if;
end;//
delimiter //
Actually I replaces new.table_name
instead of the name of table (posts
) directly. But as I said, it does not works. How can I fix it ?