gpt4 book ai didi

mysql - 如何在表更新时自动更新时间戳?

转载 作者:太空宇宙 更新时间:2023-11-03 10:47:25 25 4
gpt4 key购买 nike

我有一张带有新闻帖子的表格,我想在添加日期添加时间戳,并且我想在编辑帖子时更新另一个列。我希望它在 MySql 中自动发生。无需使用任何 PHP 代码。

   CREATE TABLE IF NOT EXISTS news (
id int(11) NOT NULL AUTO_INCREMENT,
data text,
date_published timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
date_edited timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);

在这种情况下,最佳做法是什么?

最佳答案

考虑使用触发器。来自MySQL docs :

A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update.

触发器示例:

CREATE TRIGGER trigger_example AFTER UPDATE ON news
FOR EACH ROW UPDATE some_table SET another_column = NEW.data;

关于mysql - 如何在表更新时自动更新时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29658856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com