MySQL 如何将“ON 更新当前时间戳”添加到现有表列

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

How to add "ON update current timestamp" to existing table column

mysql

提问by Rahul

i have column say ts_activity with datatype timestamp in MYSQL and default value to current timestamp. I want to add on update apply current time stamp to this column value.

我有列说 ts_activity 数据类型为 MYSQL 中的时间戳,默认值为当前时间戳。我想将更新应用当前时间戳添加到此列值。

I am not able to get alter query to do this. while create new table and its column i can add that, But not able to modify existing column by adding on update apply current timestamp.

我无法通过更改查询来执行此操作。在创建新表及其列时,我可以添加它,但无法通过添加更新应用当前时间戳来修改现有列。

Can some one tell me exact query to handle this. Can we alter this after creating table.

有人可以告诉我确切的查询来处理这个问题。我们可以在创建表后更改它吗?

Thanks

谢谢

回答by Ike Walker

Devart's suggestion will work, but I prefer to use MODIFY COLUMNinstead of CHANGE COLUMNif I'm not renaming the column.

Devart 的建议会起作用,但如果我不重命名列,我更喜欢使用MODIFY COLUMN而不是CHANGE COLUMN

I also assume that your ts_activity column is not nullable since you have a default, so I am setting it to NOT NULL, but that's up to you.

我还假设您的 ts_activity 列不可为空,因为您有默认值,因此我将其设置为 NOT NULL,但这取决于您。

This is the statement I would use:

这是我将使用的语句:

ALTER TABLE your_table
  MODIFY COLUMN ts_activity TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

回答by Devart

Try this query -

试试这个查询 -

ALTER TABLE table_name
  CHANGE COLUMN column_name column_name TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

Note, in the table only one field can be with 'ON UPDATE CURRENT_TIMESTAMP' option.

注意,表中只有一个字段可以带有“ON UPDATE CURRENT_TIMESTAMP”选项。