当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL timestamp自动更新时间分享

MySQL timestamp自动更新时间分享

2017年12月12日  | 移动技术网IT编程  | 我要评论

通常表中会有一个create date 创建日期的字段,其它数据库均有默认值的选项。mysql也有默认值timestamp,但在mysql中,不仅是插入就算是修改也会更新timestamp的值!

这样一来,就不是创建日期了,当作更新日期来使用比较好!

因此在mysql中要记录创建日期还得使用datetime 然后使用now() 函数完成!

1,timestamp default current_timestamp on update current_timestamp 
在创建新记录和修改现有记录的时候都对这个数据列刷新

2,timestamp default current_timestamp  在创建新记录的时候把这个
字段设置为当前时间,但以后修改时,不再刷新它

3,timestamp on update current_timestamp  在创建新记录的时候把这个字段设置为0


、自动update 和insert 到当前的时间:
表:
---------------------------------
table create table
------ --------------------------

create table `t1` (   `p_c` int(11) not null,  `p_time` timestamp not null default current_timestamp on update current_timestamp   ) engine=innodb default charset=gb2312

数据:

1 2007-10-08 11:53:35
2 2007-10-08 11:54:00

insert into t1(p_c) select 3;update t1 set p_c = 2 where p_c = 2;

数据:

1 2007-10-08 11:53:35
2 2007-10-08 12:00:37
3 2007-10-08 12:00:37

2、自动insert 到当前时间,不过不自动update。

表:
---------------------------------
table create table
------ ---------------------------

create table `t1` (   `p_c` int(11) not null,  `p_time` timestamp not null default current_timestamp  ) engine=innodb default charset=gb2312

数据:

insert into t1(p_c) select 4;update t1 set p_c = 3 where p_c = 3;

1 2007-10-08 11:53:35
2 2007-10-08 12:00:37
3 2007-10-08 12:00:37
4 2007-10-08 12:05:19


3、一个表中不能有两个字段默认值是当前时间,否则就会出错。不过其他的可以。
表:
---------------------------------
table create table
------ --------------------------

 create table `t1` (   `p_c` int(11) not null,  `p_time` timestamp not null default current_timestamp,  `p_timew2` timestamp not null default '0000-00-00 00:00:00'  ) engine=innodb default charset=gb2312

数据:
1 2007-10-08 11:53:35 0000-00-00 00:00:00
2 2007-10-08 12:00:37 0000-00-00 00:00:00
3 2007-10-08 12:00:37 0000-00-00 00:00:00
4 2007-10-08 12:05:19 0000-00-00 00:00:00


 比较之下,我的语句少了“on update current_timestamp”或多了“default current_timestamp”。如此一来,这个timestamp字段只是在数据insert的时间建立时间,而update时就不会有变化了。当然,如果你就是想达到这个目的倒也无所谓

1: 如果定义时default current_timestamp和on update current_timestamp子句都有,列值为默认使用当前的时间戳,并且自动更新。

2: 如果不使用default或on update子句,那么它等同于default current_timestamp on update current_timestamp。

3: 如果只有default current_timestamp子句,而没有on update子句,列值默认为当前时间戳但不自动更新。

4: 如果没用default子句,但有on update current_timestamp子句,列默认为0并自动更新。

5: 如果有一个常量值default,该列会有一个默认值,而且不会自动初始化为当前时间戳。如果该列还有一个on update current_timestamp子句,这个时间戳会自动更新,否则该列有一个默认的常量但不会自动更新。

    换句话说,你可以使用当前的时间戳去初始化值和自动更新,或者是其中之一,也可以都不是。(比如,你在定义的时候可以指定自动更新,但并不初始化。)下面的字段定义说明了这些情况:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网