简体   繁体   English

Mysql-创建触发器以根据另一张表中插入的行插入新行

[英]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 . 嗨,我有两个表叫做usersuserrewards 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.

相关问题 MySQL:触发在另一个表中插入一行时在一个表中插入新行 - MySQL: Trigger to Insert New Row in One Table When Another Table has a Row Inserted 创建触发器以在创建新行时将主键从一个表插入到 MySQL 中另一个表的列中 - Create trigger to insert primary key from one table upon creation of new row, into column of another table in MySQL MySQL触发器在更新后将新行插入另一个表 - Mysql trigger to insert a new row into another table after an update 创建触发器以在MySQL的另一个表中插入新行时更新表 - create trigger to update a table on inserting new row in another table in MySQL 如何创建SQL触发器以根据新插入的行中的值插入新行? - How do I create a SQL trigger to insert new rows based on a value in a newly inserted row? 查找并将行插入到另一个表中的mysql触发器 - find and insert row to another table mysql trigger 通过mySQL触发器将行插入另一个表 - Insert row into another table via mySQL trigger 根据当前插入的行在另一个表中创建一行 - Create a row in another table based on currently inserted row 我想在mysql中创建一个触发器,当在另一个表中更新一行时在表中插入一行 - I want to create a trigger in mysql which insert a row in a table when update a row in another table MySQL查询-获取未插入的ID以向表中插入新行 - MySQL query - getting not inserted ids to insert new row to a table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM