I'm trying to setup a trigger to insert a sum into a second table after insert of the first table.
The tables are:
- First Table Name: likes
Fields: feedid
Second Table Name: like_count
- Fields: total, feedid
After insert on likes table, I need to check if the feedid exists in table like_count. If not just insert it with total of 1. If it does exists, I need to update like_count.total to increment by one where likes.feedid = like_count.feedid
You can use MySQL
INSERT ... ON DUPLICATE KEYsyntax to simplify the logic of the trigger.For this to work,
feedidmust be a unique column in tablelikes_count(either it is the primary key of the column, or you need to create aUNIQUEconstraint on it). Then: