how to create a update trigger for Increase/Decrease 1 number to total votes number

前端 未结 1 1419
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 01:04

I have two table:

// posts
+----+---------+-----------+-------------+
| id |  title  |  content  | total_votes |
+----+---------+-----------+-------------+
| 1           


        
相关标签:
1条回答
  • 2021-01-26 01:48

    Yes you need to create an after insert trigger for that

    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 handling the update all remains same, only you need another trigger something as

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

    Since you have 2 post tables you will need to use that in the if condition

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

    Do the same for update trigger.

    0 讨论(0)
提交回复
热议问题