Hi I have two tables called users and userrewards. When a new row gets inserted into the users table, I want to take the userid and create a new row in the userrewards table, only if the usertype is "premium". In the userrewards table I just need to insert the userid - the rest of the fields are set to default values until the user makes changes themselves. How can I do this via a trigger?
-
1check dev.mysql.com/doc/refman/5.7/en/create-trigger.htmlrealbart– realbart2017-09-11 16:24:20 +00:00Commented Sep 11, 2017 at 16:24
Add a comment
|
1 Answer
You need to create an "after instert" trigger on user: that's the table you're watching. Now, if I guessed your column names correctly, the sql for creating the trigger should look like this:
CREATE TRIGGER user_ai AFTER INSERT ON user
FOR EACH ROW
BEGIN
IF new.usertype = 'premium' THEN
INSERT INTO userrewards (user_id) VALUES new.id;
END IF;
END;
Another example of a trigger with if statements and :old / :new values can be found here. MySQL documentatation for create trigger here. MySQL documentation for the if-syntax here.
2 Comments
Bill Karwin
MySQL does not use the colon before NEW and OLD. I think that's Oracle syntax.
realbart
Thanks, @BillKarwin. You're right: I confused MySQL with Oracle.