将字段设置为在UPDATE时自动插入时间戳? [英] Set field to automatically insert time-stamp on UPDATE?
问题描述
我有一个表,其中有一个名为product_price
的 DEC 字段,我想添加一个名为price_updated_date
的字段.有没有一种方法可以将表设置为在product_price
字段更新时自动插入当前时间戳?
I have a table with a DEC field named product_price
and I wanted to add a field called price_updated_date
. Is there a way to set the table to automatically insert the current time-stamp whenever the product_price
field has been updated?
如果没有,是否有办法将其设置为在条目完全更新时插入当前时间戳?
If not, is there a way to set it to insert the current time-stamp any time the entry is updated at all?
在这里使用触发器似乎是最好的选择.我是触发器的新手,在创建它时遇到了一些麻烦.这是我的代码:
It seems like using a trigger is the best option here. I am new to triggers and having some trouble creating it. Here is my code:
CREATE TRIGGER price_update
AFTER UPDATE ON cart_product
FOR EACH ROW
IF(OLD.product_price != NEW.product_price)
THEN
UPDATE cart_product
SET price_updated_date = CURDATE()
WHERE product_id = NEW.product_id
这给了我这个错误:
#1064-您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以找到在第8行
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 8
推荐答案
是的,在对表进行更新后创建触发器
yup, create trigger after update on your table
CREATE TRIGGER price_update AFTER UPDATE on _table_ FOR EACH ROW UPDATE _table_ SET price_updated_date = CURTIME() where id=NEW.id
这篇关于将字段设置为在UPDATE时自动插入时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!