Home > Database > Mysql Tutorial > body text

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

WBOY
Release: 2016-06-07 17:52:23
Original
1443 people have browsed it

由于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 属性选择

以上就是MySQL设置当前时间为默认值的方法介绍

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!