简体   繁体   English

将 NOW() 设置为日期时间数据类型的默认值?

[英]Set NOW() as Default Value for datetime datatype?

I have two columns in table users namely registerDate and lastVisitDate which consist of datetime data type.我在表用户中有两列,即registerDate and lastVisitDate ,它们由 datetime 数据类型组成。 I would like to do the following.我想做以下事情。

  1. Set registerDate defaults value to MySQL NOW()将 registerDate 默认值设置为 MySQL NOW()
  2. Set lastVisitDate default value to 0000-00-00 00:00:00 Instead of null which it uses by default.将 lastVisitDate 默认值设置为0000-00-00 00:00:00而不是默认使用的 null。

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;

It gives me Error: ERROR 1067 (42000): Invalid default value for 'registerDate'它给了我错误: ERROR 1067 (42000): Invalid default value for 'registerDate'

Is it possible for me to set the default datetime value to NOW() in MySQL?我是否可以在 MySQL 中将默认日期时间值设置为 NOW()?

As of MySQL 5.6.5, you can use the DATETIME type with a dynamic default value:从 MySQL 5.6.5 开始,您可以使用具有动态默认值的DATETIME类型:

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

Reference:参考:
http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html 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 http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html

Prior to 5.6.5, you need to use the TIMESTAMP data type, which automatically updates whenever the record is modified.在 5.6.5 之前,您需要使用TIMESTAMP数据类型,它会在记录被修改时自动更新。 Unfortunately, however, only one auto-updated TIMESTAMP field can exist per table.然而不幸的是,每个表只能存在一个自动更新的TIMESTAMP字段。

CREATE TABLE mytable (
  mydate TIMESTAMP
)

See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html请参阅: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

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:如果您想阻止 MySQL 在UPDATE上更新时间戳值(以便它仅在INSERT上触发),您可以将定义更改为:

CREATE TABLE mytable (
  mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)

I use a trigger as a workaround to set a datetime field to NOW() for new inserts:我使用触发器作为解决方法,将日期时间字段设置为 NOW() 以进行新插入:

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

it should work for updates too它也应该适用于更新

Answers by Johan & Leonardo involve converting to a timestamp field. Johan & Leonardo 的回答涉及转换为时间戳字段。 Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution.虽然这对于问题中提出的用例(存储 RegisterDate 和 LastVisitDate)可能没问题,但它不是一个通用的解决方案。 See datetime vs timestamp question.请参阅日期时间与时间戳问题。

My solution我的解决方案

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

EUREKA !!!尤里卡!!!


For all those who lost heart trying to set a default DATETIME value in MySQL , I know exactly how you feel/felt.对于那些试图在 MySQL 中设置默认 DATETIME 值的人来说,我确切地知道您的感受/感受。 So here it is:所以这里是:

`ALTER TABLE  `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0

Carefully observe that I haven't added single quotes/double quotes around the 0 .仔细观察我没有0周围添加单引号/双引号。


Important update :重要更新

This answer was posted long back.这个答案很久以前就发布了。 Back then, it worked on my (probably latest) installation of MySQL and I felt like sharing it.那时,它适用于我(可能是最新的)安装的 MySQL,我想分享它。 Please read the comments below before you decide to use this solution now.在您决定现在使用此解决方案之前,请阅读以下评论。

On versions mysql 5.6.5 and newer, you can use precise datetimes and set default values as well.在 mysql 5.6.5 和更高版本上,您也可以使用精确的日期时间并设置默认值。 There is a subtle bit though, which is to pass in the precision value to both the datetime and the NOW() function call.不过有一点微妙之处,就是将精度值传递给 datetime 和 NOW() function 调用。

This Example Works:此示例有效:

    ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW(6);

This Example Does not Work:此示例不起作用:

    ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW();

mysql 5.6 docs say that CURRENT_TIMESTAMP can be used as default for both TIMESTAMP and DATETIME data types: mysql 5.6 文档说 CURRENT_TIMESTAMP 可以用作 TIMESTAMP 和 DATETIME 数据类型的默认值:

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

`ALTER TABLE  `table_name` CHANGE `column_name` 
    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP

Can be used to update the timestamp on update.可用于在更新时更新时间戳。

The best way is using "DEFAULT 0".最好的方法是使用“DEFAULT 0”。 Other way:另一种方式:

    /************ 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();

This worked for me, using MySQL:这对我有用,使用 MySQL:

ALTER TABLE `table_name` MODIFY `column_name` datetime NOT NULL DEFAULT NOW();
ALTER TABLE table_name
  CHANGE COLUMN date_column_name date_column_name DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Finally, This worked for me!最后,这对我有用!

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
  `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mobile_UNIQUE` (`mobile`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

This worked for me - just changed INSERT to UPDATE for my table.这对我有用 - 只是将我的表的 INSERT 更改为 UPDATE 。

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

Not sure if this is still active but here goes.不确定这是否仍然有效,但这里有。

Regarding setting the defaults to Now(), I don't see that to be possible for the DATETIME data type.关于将默认值设置为 Now(),我认为 DATETIME 数据类型不可能。 If you want to use that data type, set the date when you perform the insert like this:如果要使用该数据类型,请在执行插入时设置日期,如下所示:

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

My version of mySQL is 5.5我的 mySQL 版本是 5.5

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

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