您好,欢迎来到55游戏网。
搜索
您的当前位置:首页MySQL设置当前时间为默认值方法

MySQL设置当前时间为默认值方法

来源:55游戏网


由于MySQL目前字段的默认值不支持函数,所以用create_time datetime default now()的形式设置默认值是不可能的。

代替的方案是使用TIMESTAMP类型代替DATETIME类型。
CURRENT_TIMESTAMP :当我更新这条记录的时候,这条记录的这个字段不会改变。
CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP :当我更新这条记录的时候,这条记录的这个字段将会改变。即时间变为了更新时候的时间。

(注意一个UPDATE设置一个列为它已经有的值,这将不引起TIMESTAMP列被更新,因为如果你设置一个列为它当前的值,MySQL为了效率而忽略更改。)如果有多个TIMESTAMP列,只有第一个自动更新。

下面为您介绍MySQL设置当前时间为默认值的实现全步骤

数据库:test_db1

创建表:test_ta1

字段:

id 编号(自增 且为主键),

createtime 创建日期(默认值为当前时间)

方法一、用alert table语句创建:

代码如下

use test_db1; create table test_ta1( id mediumint(8) unsigned not nulll auto_increment, createtime datetime, primary key (id) )engine=innodb default charset=gbk; alert table test_ta1 change createtime createtime timestamp not null default now();

方法二、直接创建:

代码如下

use test_db1; create table test_ta1( id mediumint(8) unsigned not nulll auto_increment, createtime timestamp not null default current_timestamp, primary key (id) )engine=innodb default charset=gbk;

方法三、使用可视化工具(如 mysql-front)创建

右击createtime属性

把Type属性值改为timestamp

default 属性选择

Copyright © 2019- 55spj.com 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务