sql >> Database teknologi >  >> RDS >> Mysql

hvordan man opretter en opdateringstrigger for Øg/Sænk 1 tal til det samlede antal stemmer

Ja, du skal oprette en after insert trigger for 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 //

For at håndtere opdateringen forbliver alt det samme, kun du behøver en anden trigger noget 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 //

Da du har 2 post-tabeller, skal du bruge det i if-tilstanden

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 det samme for opdateringstrigger.




  1. MySql, PHP display Billede på HTML

  2. Forskellen mellem InnoDB og MyISAM?

  3. Sådan komprimeres din database, så den kører hurtigere

  4. Spotlight Cloud Basic:Bedste gratis værktøj til overvågning af databaseydeevne