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

2022-01-05 00:00:00 mysql phpmyadmin

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

CREATE TABLE 日期(id int NOT NULL,id_date 日期时间 NOT NULL DEFAULT CURDATE(),主键 (id))

但是我收到以下错误:

它以红色显示CURDATE()",所以我想这就是问题所在.

有人可以帮我吗?

解决方案

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

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

示例 SQL 代码:

CREATE TABLE 日期(id int NOT NULL,id_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,主键 (id));插入日期 (id) 值 (1);SELECT id, DATE(id_date) AS id_date FROM 日期;

结果:

<前>id id_date1 2010-09-12

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

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

However I get the following error:

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

Could anyone help me out here ?

解决方案

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

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

Example SQL code:

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

相关文章