Bipin Chandra Tripathi
Bipin Chandra Tripathi

Reputation: 2620

How do I use a MySQL trigger to update multiple tables when a condition is true?

I am trying to create a trigger to update another table with a condition check, but I keep getting a MySQL error. The code for my trigger is:

DELIMITER $$
CREATEb
TRIGGER visitor_validation
BEFORE INSERT ON ratingsvisitors
FOR EACH ROW
BEGIN
Set @counts=(SELECT count(*) from ratingsvisitors where visotrid=new.userid AND  profileid=New.profileid AND itemid=New.itemid AND likevalidation=New.likevalidation AND likesordislike=New.likesordislike);
SET @ifexists = (SELECT * FROM ratingcounttracks WHERE userid=New.userid AND likedate=New.likevalidation AND countfor=New.likesordislike);
IF (@ifexists = NULL) THEN
INSERT INTO  ratingsvisitors(userid, likedate, clickcount,countfor) values (New.userid, New.likevalidation ,'1',New.likesordislike);
ELSE
UPDATE ratingsvisitors SET clickcount=clickcount+1 WHERE userid=New.userid AND likedate=New.likevalidation AND countfor=New.likesordislike;
ENDIF;
END$$

MySQL shows the error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; END' at line 12

Upvotes: 3

Views: 2707

Answers (1)

Janne
Janne

Reputation: 56

you can do something like this

DELIMITER $$
CREATE
TRIGGER visitor_validation
BEFORE INSERT ON ratingsvisitors
FOR EACH ROW
BEGIN
Set @counts=(SELECT count(*) from ratingsvisitors where visotrid=new.userid AND     
profileid=New.profileid AND itemid=New.itemid AND likevalidation=New.likevalidation AND  
likesordislike=New.likesordislike);
IF NOT EXISTS (SELECT * FROM ratingcounttracks WHERE userid=New.userid AND   
likedate=New.likevalidation AND countfor=New.likesordislike);
THEN
INSERT INTO  ratingsvisitors(userid, likedate, clickcount,countfor) values (New.userid, 
New.likevalidation ,'1',New.likesordislike);
ELSE
UPDATE ratingsvisitors SET clickcount=clickcount+1 WHERE userid=New.userid AND 
likedate=New.likevalidation AND countfor=New.likesordislike;
ENDIF;
END$$

Upvotes: 3

Related Questions