MySQL 添加以当前时间为默认值的新列

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

Adding a new column with the current time as a default value

mysqlsqltimestampddl

提问by RedPe4rl

I am looking for the syntax to add a column to a MySQL table with the current time as a default value.

我正在寻找将列添加到 MySQL 表的语法,并将当前时间作为默认值。

回答by Roman Marusyk

IMPORTANT EDIT:It is now possible to achieve this with DATETIMEfields since MySQL 5.6.5, take a look at the other postbelow...

重要编辑:现在可以使用MySQL 5.6.5DATETIME以来的字段来实现这一点,看看下面的一篇文章......

It is now possible to achieve this with DATETIMEfields since MySQL 5.6.5
But you can do it with TIMESTAMP:

DATETIME从 MySQL 5.6.5 开始,现在可以使用字段来实现这一点,
但您可以使用TIMESTAMP

 create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP)

回答by Zafar Malik

Even so many persons have provided solution but this is just to add more information-

即使有这么多人提供了解决方案,但这只是为了添加更多信息-

If you just want to insert current timestamp at the time of row insertion-

如果您只想在行插入时插入当前时间戳 -

ALTER TABLE mytable ADD mytimestampcol TIMESTAMP DEFAULT CURRENT_TIMESTAMP;

If you also want that this column should update if any update this row then use this-

如果您还希望此列在更新此行时更新,则使用此 -

ALTER TABLE mytable ADD mytimestampcol TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

回答by Mureinik

You can specify a defaultclause:

您可以指定一个default子句:

ALTER TABLE mytable ADD COLUMN (mytimestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

回答by Venkatesh Panabaka

I think these sql will useful to you.

我认为这些 sql 对你有用。

create table test (column_name varchar(32), time_column TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

mysql> insert into test (column_name) values ("demo");
Query OK, 1 row affected (0.00 sec)

mysql> select column_name as name, time_column as ts from  test;
+------+---------------------+
| name | ts                  |
+------+---------------------+
| demo | 2014-07-31 15:42:52 | 
+------+---------------------+

1 row in set (0.00 sec)

1 行(0.00 秒)

Thank you.

谢谢你。

回答by Manish Sapkal

create table test (col1 varchar(10), lastaccessdate TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6));

this will update time with fractional seconds in time, and also update when record is last inserted or updated.

这将更新时间以秒为单位,并在上次插入或更新记录时更新。