MySQL 触发“列更新”语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10356967/
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 13:09:05  来源:igfitidea点击:

MySQL trigger 'update on column' syntax

mysqlsyntaxtriggerssql-update

提问by cldy1020

Can we use a MySQL trigger on update of specific columns, which updates another column in same table (same row)

我们可以在更新特定列时使用 MySQL 触发器,它更新同一表(同一行)中的另一列

create trigger my_trigger
BEFORE UPDATE OF col1, col2 ON TABLE_NAME
for each row
set NEW.col3 =  NEW.col3 +1;

I tried the above code using UPDATE OF col1, col2. It is not working in MySQL. What is the correct syntax, can somebody point me to some examples.

我使用UPDATE OF col1, col2. 它在 MySQL 中不起作用。什么是正确的语法,有人可以指点我一些例子。

回答by eggyal

You can't specify that the trigger is to be run only on the update of specific columns (an UPDATEaffects the entire record), but you can test which columns have been updated within your trigger:

您不能指定触发器仅在更新特定列时运行(UPDATE影响整个记录),但您可以测试哪些列已在您的触发器中更新:

DELIMITER ;;

CREATE TRIGGER my_trigger BEFORE UPDATE ON TABLE_NAME FOR EACH ROW
IF NOT (NEW.col1 <=> OLD.col1 AND NEW.col2 <=> OLD.col2) THEN
  SET NEW.col3 = NEW.col3 + 1;
END IF;;

DELIMITER ;