使用默认值当前日期时间 MYSQL 创建一列“日期" [英] Create a column 'Date' with default value current datetime MYSQL

查看:105
本文介绍了使用默认值当前日期时间 MYSQL 创建一列“日期"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的 SQL 查询,它抛出一个错误:-

Following is my SQL query, it throws an error:-

CREATE TABLE IF NOT EXISTS USER_PROFILE(Id INT PRIMARY KEY AUTO_INCREMENT, date DATETIME NOT NULL DEFAULT NOW) ;

它说'date'的默认值无效.

我也尝试过 NOW() 的同义词,即 CURRENT_TIMESTAMP,但还是出现同样的错误.

I've tried synonyms for NOW() as well, namely CURRENT_TIMESTAMP, but still the same error.

如何使用默认值当前时间创建列日期?

How can I create a column date with default value current time?

在文档页面上,它说以这种方式分配

On the documentation page, it says to assign this way

CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  dt DATETIME DEFAULT CURRENT_TIMESTAMP
);

推荐答案

来自文档

数据类型规范中的 DEFAULT 值子句表示列的默认值.除了一个例外,默认值必须是一个常数;它不能是函数或表达式.这表示,例如,您不能将日期列的默认值设置为NOW() 或 CURRENT_DATE 等函数的值.例外是您可以指定 CURRENT_TIMESTAMP 作为 TIMESTAMP 的默认值和 DATETIME 列

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

因此默认值中不允许使用任何函数,因此第一个查询失败.

So no function is allowed in the default value hence the first query is failing.

再次来自文档

从 MySQL 5.6.5 开始,可以自动设置 TIMESTAMP 和 DATETIME 列初始化并更新为当前日期和时间(即当前时间戳).在 5.6.5 之前,这仅适用于 TIMESTAMP,并且每个表最多有一个 TIMESTAMP 列.先做以下注意事项描述 MySQL 5.6.5 及更高版本的自动初始化和更新,然后是 5.6.5 之前版本的差异.

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 因此第二个查询也失败了.

So your mysql version is less than 5.6.5 hence the 2nd query is failing too.

因此您需要将表创建为

CREATE TABLE IF NOT EXISTS 
USER_PROFILE
(
  Id INT PRIMARY KEY AUTO_INCREMENT, 
  date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ;

这篇关于使用默认值当前日期时间 MYSQL 创建一列“日期"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆