MySQL 如何从mysql5触发器中的选择查询中获取值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5041495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:49:59  来源:igfitidea点击:

how to get value from select query in trigger in mysql5?

mysqlsqltriggers

提问by Yugal

How to get value from select query in trigger and insert that value in table?

如何从触发器中的选择查询中获取值并将该值插入表中?

回答by RolandoMySQLDBA

For an INSERT Trigger query you would use the object NEW
For an UPDATE Trigger query you would use the object OLD and NEW
For a DELETE Trigger query you would use the object OLD

对于 INSERT 触发器查询,您将使用对象 NEW
对于更新触发器查询,您将使用对象 OLD 和 NEW
对于 DELETE 触发器查询,您将使用对象 OLD

Example 1 : iF you ran INSERT INTO mytable (num) VALUES (10);
In the INSERT trigger, you reference the column as NEW.num (10);

示例 1:如果您运行 INSERT INTO mytable (num) VALUES (10);
在 INSERT 触发器中,您将该列引用为 NEW.num (10);

Example 2 : iF you ran UPDATE mytable SET num = 41 WHERE num = 10;
In the UPDATE trigger, you reference OLD.num (10) and NEW.num (41)

示例 2:如果您运行 UPDATE mytable SET num = 41 WHERE num = 10;
在 UPDATE 触发器中,您引用 OLD.num (10) 和 NEW.num (41)

Example 3 : iF you ran DELETE mytable num = 104;
In the DELETE trigger, you reference OLD.num (104)

示例 3:如果您运行 DELETE mytable num = 104;
在 DELETE 触发器中,您引用 OLD.num (104)

Use something like this:

使用这样的东西:

DELIMITER $$

create trigger my_trigger
AFTER UPDATE on my_update_table
for each row
begin

    DECLARE P1,P2 VARCHAR(50);

    SELECT PRICENAME INTO P1 FROM PRICEIES WHERE PRICEID=OLD.PRICEID;
    SELECT PRICENAME INTO P2 FROM PRICEIES WHERE PRICEID=NEW.PRICEID;
    INSERT INTO AUDITLOG(OLDVALUE, NEWVALUE) VALUES (P1,P2);

end $$

DELIMITER ;