简体   繁体   English

如何更改mysql表列的默认值?

[英]How do I alter a mysql table column defaults?

I have a table with a column of type timestamp which defaults current_timestamp and updates to current_timestamp on every update. 我有一个表格,其中包含timestamp类型的列,默认为current_timestamp并在每次更新时更新为current_timestamp

I want to remove the "on update" feature on this column. 我想删除此列上的“on update”功能。 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. 但这没用。

Pete was almost correct but used the wrong syntax for 'change': Pete几乎是正确的但是使用了错误的语法来“改变”:

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. 通过指定CURRENT_TIMESTAMP的DEFAULT,MySQL将不再自动更新列。 From the MySQL Manual : 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子句时,该列具有其默认值的当前时间戳,但不会自动更新。

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) (编辑添加转义和第二次使用字段名称)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM