sql >> Base de Datos >  >> RDS >> Mysql

cómo crear un activador de actualización para aumentar/disminuir 1 número al número total de votos

Sí, debe crear un after insert trigger por eso

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 //

Para manejar la actualización, todo sigue igual, solo necesita otro desencadenante algo como

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 //

Como tiene 2 tablas de publicaciones, deberá usarlas en la condición if

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 //

Haga lo mismo para el activador de actualización.