由于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();
发卡宝-卡密寄售系统
下载
发卡宝是一个专业的软件卡密等虚拟商品在线交易平台,拥有多种兑换方式,费率低,结算快,正规企业平台一直稳定运营,24小时不间断提供自动发卡服务。【模板说明】试用版自带一套模板(响应式)【环境支持】PHP环境 / 200M或以上空间大小 / 开启父路径 / 设置index.php为默认首页 / 目录写入权限需要开启【数据库】MySQL【安装步骤】将文件上传至空间目录,运行“http://域名/inst |
|
方法二、直接创建:
| 代码如下 | 复制代码 |
|
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 属性选择
以上就是MySQL设置当前时间为默认值的方法介绍










