设置字段以在更新时自动插入时间戳?
我有一个表,其中有一个名为 product_price
的 DEC 字段,我想添加一个名为 price_updated_date
的字段。有没有办法将表设置为在 product_price
字段更新时自动插入当前时间戳?
如果没有,是否有办法将其设置为在条目更新时插入当前时间戳?
更新:
似乎使用触发器是这里的最佳选择。我对触发器不熟悉,在创建它时遇到一些麻烦。这是我的代码:
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 行 '' 附近使用的正确语法
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?
update:
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
This is giving me this error:
#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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不将该字段的属性设置为:
Why not set properties for that field as:
是的,在表更新后创建触发器
CREATE TRIGGER Price_update AFTER UPDATE on _table_ FOR EACH ROW UPDATE _table_ SET Price_updated_date = CURTIME() where id=NEW.id
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
我注意到您正在使用 MySQL
MySQL 时间戳字段的默认行为是在插入和更新时默认为 NOW()
http://dev.mysql.com/doc/refman/5.0/en/timestamp.html
我知道这并不取决于您更新了哪一列需要,但可能对您或浏览此问题的其他人有用。
这是一个 5 秒的工作 - 只需添加一个时间戳字段和嘿急
I note you're using MySQL
The default behaviour of a MySQL timestamp field is to default to NOW() on insert AND on update
http://dev.mysql.com/doc/refman/5.0/en/timestamp.html
I know this isn't dependant on which column has been updated as you require, but may be of some use to you or someone else browsing this question.
Its a 5-second job - just add a timestamp field & hey presto
每当您运行更新语句时,请确保执行以下操作:
当您更改行时,这将始终插入当前日期/时间。
Anytime you run an update statement, make sure you do something like this:
This will always insert the current date/time when you change the row.
使用数据库触发器:
http://dev.mysql.com/doc/ refman/5.0/en/triggers.html
Use a database trigger:
http://dev.mysql.com/doc/refman/5.0/en/triggers.html