如何更改 mysql 表列默认值?

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

How do I alter a mysql table column defaults?

mysqldatabasetimestampalter

提问by Tihom

I have a table with a column of type timestampwhich defaults current_timestampand updates to current_timestampon every update.

我有一个带有类型列的表,该列在每次更新时timestamp默认current_timestampcurrent_timestamp更新。

I want to remove the "on update" feature on this column. How do I write the alter statement?

我想删除此列上的“更新时”功能。我如何写alter语句?

I tried the following:

我尝试了以下方法:

ALTER TABLE mytable alter column time  set DEFAULT now();

but this didn't work.

但这没有用。

回答by jonstjohn

Pete was almost correct but used the wrong syntax for 'change':

皮特几乎是正确的,但使用了错误的“更改”语法:

ALTER TABLE mytable CHANGE `time` `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Notice that you must repeat the column name. Also, make sure you are using backticks instead of single quotes to escape the column name time, which prevents it from being interpreted as the mysql column type of time.

请注意,您必须重复列名。另外,请确保您使用反引号而不是单引号来转义列名时间,这可以防止它被解释为 mysql 列类型的时间。

By specifying the DEFAULT of CURRENT_TIMESTAMP, MySQL will no longer automatically update the column. From the MySQL Manual:

通过指定 CURRENT_TIMESTAMP 的 DEFAULT,MySQL 将不再自动更新该列。从MySQL 手册

With a DEFAULT CURRENT_TIMESTAMP clause and no ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated.

使用 DEFAULT CURRENT_TIMESTAMP 子句而没有 ON UPDATE 子句时,列的默认值具有当前时间戳,但不会自动更新。

回答by Pete

You can't AFAIK use functions such as NOW() as a default.

您不能 AFAIK 使用 NOW() 等函数作为默认值。

Try

尝试

ALTER TABLE `mytable` CHANGE `time` `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

(Edited to add escaping and second use of field name)

(编辑添加转义和字段名称的第二次使用)