简体   繁体   English

MySQL表上的触发器

[英]Triggers on MySQL table

Helllo, I have the following table Scores : 地狱,我有下表Scores

ID
Name
Value
Creation_date
Modification_date

I also have table Scores_History : 我也有表Scores_History

ID
Name
Value
Creation_date

What I need to do is to set a trigger, so when a row in table Scores is updated, it will store the old Name and Value inside the Scores_History table (create a new row). 我需要做的是设置一个触发器,所以当表Scores的一行更新时,它将在Scores_History表中存储旧的NameValue (创建新行)。

Can someone help me to figure out the query, since nothing I tried is working. 有人可以帮我解决该查询,因为我尝试过的任何方法都没有用。

You want something like this: 您想要这样的东西:

CREATE TRIGGER yourtrigger BEFORE UPDATE ON `Scores`
FOR EACH ROW
BEGIN
    INSERT INTO `Scores_History` (Name, Value, Creation_date) VALUES(OLD.Name, OLD.Value, OLD.Creation_date);
END $$
DELIMITER;

Docs: http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html 文件: http//dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html

Similar: MySQL Triggers insert into another table 相似: MySQL触发器插入另一个表

Something like this, assuming the id column in scores_history is auto_increment: 像这样,假设scores_history中的id列为auto_increment:

DELIMITER $$

CREATE TRIGGER scores_bu
BEFORE UPDATE ON scores
FOR EACH ROW
BEGIN
   INSERT INTO scores_history (name, value, creation_date)
   VALUES (OLD.name, OLD.value, OLD.creation_date);
END$$

DELIMITER ;

Actually, you probably want the "creation_date" column to contain the current date and time, rather than the value from the scores table. 实际上,您可能希望"creation_date"列包含当前日期和时间,而不是scores表中的值。

To get that behavior, modify the trigger to replace the reference to "OLD.creation_date" with a reference to "NOW()" . 要获得该行为,请修改触发器,以将对"OLD.creation_date"的引用替换为对"NOW()"的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM