使用 CURDATE() 作为默认值时,在 mysql 中创建表失败

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

Create table fail in mysql when using CURDATE() as default

mysqlphpmyadmin

提问by Goles

I'm trying to create the following table using phpmyadmin sql console:

我正在尝试使用 phpmyadmin sql 控制台创建下表:

CREATE TABLE dates
(
id int NOT NULL,
id_date datetime NOT NULL DEFAULT CURDATE(),
PRIMARY KEY (id)
)

However I get the following error: alt text

但是我收到以下错误: 替代文字

It shows "CURDATE()" in red, so I guess that's the problem.

它以红色显示“CURDATE()”,所以我想这就是问题所在。

Could anyone help me out here ?

有人可以帮我吗?

回答by Mark Byers

You can't use CURDATE() as a default value.

您不能使用 CURDATE() 作为默认值。

Instead you can use a TIMESTAMP column with DEFAULT CURRENT_TIMESTAMP. Then you will have to ignore the time part of it.

相反,您可以使用带有 DEFAULT CURRENT_TIMESTAMP 的 TIMESTAMP 列。那么你将不得不忽略它的时间部分。

Example SQL code:

示例 SQL 代码:

CREATE TABLE dates
(
    id int NOT NULL,
    id_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);
INSERT INTO dates (id) VALUES (1);
SELECT id, DATE(id_date) AS id_date FROM dates;

Result:

结果:

id  id_date
1   2010-09-12