将NOW()设置为datetime数据类型的默认值? [英] Set NOW() as Default Value for datetime datatype?
问题描述
我在表用户中有两列,即 registerDate和lastVisitDate
,它由datetime数据类型组成。我想执行以下操作。
I have two columns in table users namely registerDate and lastVisitDate
which consist of datetime data type. I would like to do the following.
- 将registerDate默认值设置为MySQL NOW()
- 将lastVisitDate默认值设置为
0000-00-00 00:00:00
而不是默认使用的null。
- Set registerDate defaults value to MySQL NOW()
- Set lastVisitDate default value to
0000-00-00 00:00:00
Instead of null which it uses by default.
因为表已经存在并且有现有的记录,我想使用Modify表。我试过使用下面的两段代码,但是两者都不行。
Because the table already exists and has existing records, I would like to use Modify table. I've tried using the two piece of code below, but neither works.
ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;
它给我错误:错误1067(42000):无效的默认值'registerDate'
我可以在MySQL中将默认的datetime值设置为NOW()吗?
Is it possible for me to set the default datetime value to NOW() in MySQL?
推荐答案
从MySQL 5.6.5开始,您可以使用动态默认值的 DATETIME
类型:
As of MySQL 5.6.5, you can use the DATETIME
type with a dynamic default value:
CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)
甚至可以组合这两个规则:
Or even combine both rules:
modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
参考: >
http://dev.mysql.com/ doc / refman / 5.7 / en / timestamp-initialization.html
http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html
在5.6.5之前,您需要使用 TIMESTAMP
数据类型,它会自动更新记录被修改。但是,不幸的是,每个表只能有一个自动更新的 TIMESTAMP
字段。
Prior to 5.6.5, you need to use the TIMESTAMP
data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated TIMESTAMP
field can exist per table.
CREATE TABLE mytable (
mydate TIMESTAMP
)
请参阅: a href =http://dev.mysql.com/doc/refman/5.1/en/create-table.html =noreferrer> http://dev.mysql.com/doc/refman/5.1/ en / create-table.html
See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
如果要阻止MySQL更新 UPDATE $ c $时的时间戳记值c>(以便只在
INSERT
中触发),您可以将定义更改为:
If you want to prevent MySQL from updating the timestamp value on UPDATE
(so that it only triggers on INSERT
) you can change the definition to:
CREATE TABLE mytable (
mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
这篇关于将NOW()设置为datetime数据类型的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!