以下是我的 SQL 查询,它抛出一个错误:-
CREATE TABLE IF NOT EXISTS USER_PROFILE(Id INT PRIMARY KEY AUTO_INCREMENT, date DATETIME NOT NULL DEFAULT NOW) ;
它显示“日期”的默认值无效
。
我也尝试过 NOW()
的同义词,即 CURRENT_TIMESTAMP
,但仍然是相同的错误。
如何创建具有默认值当前时间的列日期?
在文档页面上,它说要这样分配
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
dt DATETIME DEFAULT CURRENT_TIMESTAMP
);
最佳答案
摘自文档
The DEFAULT value clause in a data type specification indicates a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for TIMESTAMP and DATETIME columns
因此默认值中不允许使用任何函数,因此第一个查询失败。
再次来自文档
As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically initializated and updated to the current date and time (that is, the current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and for at most one TIMESTAMP column per table. The following notes first describe automatic initialization and updating for MySQL 5.6.5 and up, then the differences for versions preceding 5.6.5.
Before 5.6.5, this is true only for TIMESTAMP
所以你的mysql版本低于5.6.5
,因此第二个查询也失败了。
因此您需要将表创建为
CREATE TABLE IF NOT EXISTS
USER_PROFILE
(
Id INT PRIMARY KEY AUTO_INCREMENT,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ;
关于mysql - 创建列 'Date',默认值为当前日期时间 MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28966698/