mysql - 创建列 'Date',默认值为当前日期时间 MYSQL

标签 mysql

以下是我的 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/

相关文章:

mysql - 在表上执行 SELECT 时我是否锁定表?

android - 我可以在没有任何 web 服务的情况下使用 JDBC 从 android 连接到 mysql 吗?

php - CakePHP 中的自定义验证规则

mysql - 如何在ORDER BY中使用CASE函数?

MySQL docker 中的 MySQL conf 文件

php - 了解 mysql 连接如何工作

MySQL 连接提示输入密码,即使它在连接字符串中

Java JDBC Web MySql 通信

mysql - 选择每首歌曲中观看次数最多的视频

从另一个终端输出的php脚本