如何为 MySQL 日期时间列设置默认值?

2021-11-20 00:00:00 datetime mysql

如何为 MySQL 日期时间列设置默认值?

How do you set a default value for a MySQL Datetime column?

在 SQL Server 中,它是 getdate().MySQL 的等效项是什么?如果这是一个因素,我正在使用 MySQL 5.x.

In SQL Server it's getdate(). What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.

推荐答案

重要从 MySQL 5.6.5 开始,现在可以使用 DATETIME 字段来实现这一点,请查看 其他帖子 下面...

IMPORTANT It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below...

以前的版本不能用 DATETIME...

Previous versions can't do that with DATETIME...

但是你可以用 TIMESTAMP 来做到:

But you can do it with TIMESTAMP:

mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected (0.00 sec)

mysql> desc test;
+-------+-------------+------+-----+-------------------+-------+
| Field | Type        | Null | Key | Default           | Extra |
+-------+-------------+------+-----+-------------------+-------+
| str   | varchar(32) | YES  |     | NULL              |       | 
| ts    | timestamp   | NO   |     | CURRENT_TIMESTAMP |       | 
+-------+-------------+------+-----+-------------------+-------+
2 rows in set (0.00 sec)

mysql> insert into test (str) values ("demo");
Query OK, 1 row affected (0.00 sec)

mysql> select * from test;
+------+---------------------+
| str  | ts                  |
+------+---------------------+
| demo | 2008-10-03 22:59:52 | 
+------+---------------------+
1 row in set (0.00 sec)

mysql>

CAVEAT: 如果您定义了一个默认设置为 CURRENT_TIMESTAMP ON 的列,您将需要始终为此列指定一个值,否则该值将自动重置为now()"在更新.这意味着如果您不想更改该值,则您的 UPDATE 语句必须包含[您的列名] = [您的列名]";(或某个其他值)或该值将变为now()".很奇怪,但确实如此.我正在使用 5.5.56-MariaDB

相关文章