MySQL 如何将 DATE(不是 DATETIME/TIMESTAMP)列的默认值设置为当前日期?

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

How to set default value of DATE (not DATETIME/TIMESTAMP) column to current date?

mysql

提问by Dmitrij Kultasev

NOTE: The question is about DATE type, not Datetime or Timestamp

注意:问题是关于日期类型,而不是日期时间或时间戳

How to alter column of date data type to use current date by default? I saw a lot of examples for datetime, but not for date. I have tried:

如何更改日期数据类型的列以默认使用当前日期?我看到了很多关于日期时间的例子,但没有看到日期。我试过了:

ALTER TABLE `accounting` ALTER `accounting_date` SET DEFAULT CURRENT_DATE;
ALTER TABLE `accounting` CHANGE `accounting_date` `accounting_date` DATE NOT NULL DEFAULT CURRENT_DATE;

I also tried with CURDATE(), NOW(), CURRENT_DATE() ...

我也尝试过 CURDATE(), NOW(), CURRENT_DATE() ...

采纳答案by 1000111

Probably you cannot set default value for 'date' data type in mysql. You need to change the type to timestamp or datetime.

您可能无法在 mysql 中为“日期”数据类型设置默认值。您需要将类型更改为时间戳或日期时间。

You may have a look at this similar question.

你可以看看这个类似的问题。

Invalid default value for 'Date'

“日期”的默认值无效

EDIT:

编辑:

In version 5.6.5, it is possible to set a default value on a datetime column, and even make a column that will update when the row is updated. The type definition:

在 5.6.5 版本中,可以在日期时间列上设置默认值,甚至可以创建一个在行更新时更新的列。类型定义:

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

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

回答by The Godfather

As noted in this question Invalid default value for 'create_date' timestamp field, this error may happen when MySQL is in strictmode (which is default behavior, I believe).

正如这个问题Invalid default value for 'create_date' timestamp field 中所述,当 MySQL 处于strict模式时可能会发生此错误(我相信这是默认行为)。

If you want to override it, just disable all these checks when creating your table:

如果要覆盖它,只需在创建表时禁用所有这些检查:

SET SQL_MODE='ALLOW_INVALID_DATES';

The warning will be still generated, however it will allow to create the table.

仍然会生成警告,但它会允许创建表。