如何设置MySQL Datetime列的默认值? [英] How do you set a default value for a MySQL Datetime column?
本文介绍了如何设置MySQL Datetime列的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在SQL Server中,这是 getdate()
。什么是MySQL的等价物?我使用MySQL 5.x,如果这是一个因素。
解决方案
重要编辑
现在可以使用DATETIME字段来实现这一点,因为MySQL 5.6.5 可以看看其他帖子以下...
以前的版本不能用DATETIME ...
但是您可以使用TIMESTAMP:
mysql>创建表测试(str varchar(32),ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
查询OK,0行受影响(0.00秒)
mysql>描述测试
+ ------- + ------------- + ------ + ----- + ---------- --------- + ------- +
| Field |类型|空|关键|默认|额外|
+ ------- + ------------- + ------ + ----- + ---------- --------- + ------- +
| str | varchar(32)|是| | NULL | |
| ts |时间戳| NO | | CURRENT_TIMESTAMP | |
+ ------- + ------------- + ------ + ----- + ---------- --------- + ------- +
2行集(0.00秒)
mysql>插入test(str)值(demo);
查询OK,1行受影响(0.00秒)
mysql>从测试中选择*
+ ------ + --------------------- +
| str | ts |
+ ------ + --------------------- +
|演示| 2008-10-03 22:59:52 |
+ ------ + --------------------- +
1行集(0.00秒)
mysql>
How do you set a default value for a MySQL Datetime column?
In SQL Server it's getdate()
. What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.
解决方案
IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below...
Previous versions can't do that with DATETIME...
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>
这篇关于如何设置MySQL Datetime列的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文