[英]Mysql - Create trigger to insert a new row based on a row inserted in another table
Hi I have two tables called users
and userrewards
. 嗨,我有两个表叫做
users
和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". 当在用户表中插入新行时,仅当用户
usertype
为“ premium”时,我才想使用userid
并在userrewards表中创建新行。 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. 在userrewards表中,我只需要插入userid-其余字段将设置为默认值,直到用户自己进行更改。 How can I do this via a trigger?
如何通过触发器执行此操作?
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:
现在,如果我猜对了列名,则用于创建触发器的sql应该如下所示:
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 . 带有if语句和:old /:new值的触发器的另一个示例可以在此处找到。 MySQL documentatation for create trigger here .
创建触发器的MySQL文档在此处 。 MySQL documentation for the if-syntax here .
此处的if-syntax的MySQL文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.