我在表用户中有两列,即registerDate和lastVisitDate,它们由datetime数据类型组成。我想做以下事情。

将registerDate的默认值设置为MySQL NOW() 将lastVisitDate的默认值设置为0000-00-00 00:00:00,而不是默认使用的null。

因为该表已经存在,并且有已有的记录,所以我想使用修改表。我尝试使用下面的两段代码,但都不起作用。

ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;

它给我错误:错误1067(42000):无效的默认值为'registerDate'

我是否可以在MySQL中设置默认的日期时间值为NOW() ?


当前回答

这适用于我,使用MySQL:

ALTER TABLE `table_name` MODIFY `column_name` datetime NOT NULL DEFAULT NOW();

其他回答

我的解决方案

ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
NULL DEFAULT CURRENT_TIMESTAMP;

不确定这是否仍然活跃,但这里开始。

关于将默认值设置为Now(),我认为DATETIME数据类型不可能这样做。如果你想使用该数据类型,在执行插入时设置日期,如下所示:

INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))

我的mySQL版本是5.5

我使用触发器作为解决方法,为新插入设置datetime字段为NOW():

CREATE TRIGGER `triggername` BEFORE INSERT ON  `tablename` 
FOR EACH ROW 
SET NEW.datetimefield = NOW()

它也应该适用于更新

Johan和Leonardo的回答涉及到转换到时间戳字段。尽管这对于问题中提出的用例(存储RegisterDate和LastVisitDate)可能是可行的,但这不是一个通用的解决方案。参见日期时间vs时间戳问题。

mysql 5.6文档说CURRENT_TIMESTAMP可以作为TIMESTAMP和DATETIME数据类型的默认值:

http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html

最好的方法是使用“DEFAULT 0”。 其他方式:

    /************ ROLE ************/
    drop table if exists `role`;
    create table `role` (
        `id_role` bigint(20) unsigned not null auto_increment,
        `date_created` datetime,
        `date_deleted` datetime,
        `name` varchar(35) not null,
        `description` text,
        primary key (`id_role`)
    ) comment='';

    drop trigger if exists `role_date_created`;
    create trigger `role_date_created` before insert
        on `role`
        for each row 
        set new.`date_created` = now();