Ja, du måste skapa en after insert trigger
för det
delimiter //
create trigger total_votes_count after insert on votes
for each row
begin
if (new.value == 1) then
update posts set total_votes = total_votes+1
where id = new.id_post;
elseif (new.value == -1) then
update posts set total_votes = total_votes-1
where id = new.id_post;
end if;
end;//
delimiter //
För att hantera uppdateringen förblir allt detsamma, bara du behöver en annan trigger något som
delimiter //
create trigger total_votes_count_upd after update on votes
for each row
begin
if (new.value == 1) then
update posts set total_votes = total_votes+1
where id = new.id_post;
elseif (new.value == -1) then
update posts set total_votes = total_votes-1
where id = new.id_post;
end if;
end;//
delimiter //
Eftersom du har 2 inläggstabeller måste du använda det i if-villkoret
delimiter //
create trigger total_votes_count after insert on votes
for each row
begin
if (new.value == 1) then
if (new.table_name == 'post_A') then
update posts_A set total_votes = total_votes+1
where id = new.id_post;
else
update posts_B set total_votes = total_votes+1
where id = new.id_post;
end if;
elseif (new.value == -1) then
if (new.table_name == 'post_A') then
update posts_A set total_votes = total_votes-1
where id = new.id_post;
else
update posts_B set total_votes = total_votes-1
where id = new.id_post;
end if ;
end if;
end;//
delimiter //
Gör samma sak för uppdateringstrigger.