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

发布于 2024-11-04 01:08:50 字数 556 浏览 5 评论 0原文

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

  1. 将registerDate 默认值设置为MySQL NOW()
  2. 将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;

它给我错误:ERROR 1067 (42000): Invalid default value for 'registerDate'

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

I have two columns in table users namely registerDate and lastVisitDate which consist of datetime data type. I would like to do the following.

  1. Set registerDate defaults value to MySQL NOW()
  2. Set lastVisitDate default value to 0000-00-00 00:00:00 Instead of null which it uses by default.

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'

Is it possible for me to set the default datetime value to NOW() in MySQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

冰葑 2024-11-11 01:08:50

从 MySQL 5.6.5 开始,您可以使用带有动态默认值的 DATETIME 类型:

CREATE TABLE foo (
    creation_time      DATETIME DEFAULT   CURRENT_TIMESTAMP,
    modification_time  DATETIME ON UPDATE CURRENT_TIMESTAMP
)

或者甚至结合这两种规则:

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 字段。

CREATE TABLE mytable (
  mydate TIMESTAMP
)

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

如果你想阻止 MySQL 在 UPDATE 上更新时间戳值(以便它只在 INSERT 上触发)您可以将定义更改为:

CREATE TABLE mytable (
  mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)

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

Reference:
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

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
)

See: 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:

CREATE TABLE mytable (
  mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
五里雾 2024-11-11 01:08:50

我使用触发器作为解决方法,将日期时间字段设置为 NOW() 以进行新插入:

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

它也应该适用于

更新Leonardo 涉及转换为时间戳字段。尽管这对于问题中提出的用例(存储 RegisterDate 和 LastVisitDate)可能没问题,但它不是通用的解决方案。请参阅日期时间与时间戳问题。

I use a trigger as a workaround to set a datetime field to NOW() for new inserts:

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. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.

月亮是我掰弯的 2024-11-11 01:08:50

我的解决方案

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

My solution

ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
NULL DEFAULT CURRENT_TIMESTAMP;
望喜 2024-11-11 01:08:50

EUREKA !!!


对于所有那些试图在 MySQL 中设置 默认 DATETIME 值而灰心丧气的人,我完全了解您的感受。所以这里是:

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

仔细观察我没有在0周围添加单引号/双引号


重要更新

这个答案很早就发布了。当时,它在我(可能是最新的)安装的 MySQL 上运行,我想分享它。在您决定立即使用此解决方案之前,请阅读下面的评论。

EUREKA !!!


For all those who lost heart trying to set a default DATETIME value in MySQL, I know exactly how you feel/felt. 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.


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. Please read the comments below before you decide to use this solution now.

李不 2024-11-11 01:08:50

在 mysql 5.6.5 及更高版本上,您可以使用精确的日期时间并设置默认值。但有一个微妙的地方,即将精度值传递给日期时间和 NOW() 函数调用。

此示例有效:

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

此示例无效:

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

On versions mysql 5.6.5 and newer, you can use precise datetimes and set default values as well. There is a subtle bit though, which is to pass in the precision value to both the datetime and the NOW() function call.

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();
七分※倦醒 2024-11-11 01:08:50

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

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

mysql 5.6 docs say that CURRENT_TIMESTAMP can be used as default for both TIMESTAMP and DATETIME data types:

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

孤蝉 2024-11-11 01:08:50
`ALTER TABLE  `table_name` CHANGE `column_name` 
    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP

可用于更新更新时的时间戳。

`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.

时光暖心i 2024-11-11 01:08:50

最好的方法是使用“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();

The best way is using "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();
红颜悴 2024-11-11 01:08:50

这对我有用,使用 MySQL:

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

This worked for me, using MySQL:

ALTER TABLE `table_name` MODIFY `column_name` datetime NOT NULL DEFAULT NOW();
后eg是否自 2024-11-11 01:08:50
ALTER TABLE table_name
  CHANGE COLUMN date_column_name date_column_name DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

最后,这对我有用!

ALTER TABLE table_name
  CHANGE COLUMN date_column_name date_column_name DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Finally, This worked for me!

深空失忆 2024-11-11 01:08:50
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;
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;
影子的影子 2024-11-11 01:08:50

不确定这是否仍然有效,但就这样。

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

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

我的 mySQL 版本是 5.5

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. 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

笛声青案梦长安 2024-11-11 01:08:50

这对我有用 - 只是将我的表的 INSERT 更改为 UPDATE 。

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

This worked for me - just changed INSERT to UPDATE for my table.

INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文