当前位置: 移动技术网 > IT编程>数据库>Mysql > mysql多个TimeStamp设置教程

mysql多个TimeStamp设置教程

2018年09月25日  | 移动技术网IT编程  | 我要评论

timestamp设置默认值是default current_timestamp

timestamp设置随着表变化而自动更新是on update current_timestamp

可以设置2个timestape字段 只是只能把一个字段设置为默认值更新  另一个无法自动更新

但是由于mysql

一个表中至多只能有一个字段设置current_timestamp

两行设置default current_timestamp是不行的。

还有一点要注意

create table `device` (
    `id` int(10) unsigned not null auto_increment,
    `toid` int(10) unsigned not null default '0' comment 'toid',
    `createtime` timestamp not null comment '创建时间',
    `updatetime` timestamp not null default current_timestamp comment '最后更新时间',
    primary key (`id`),
    unique index `toid` (`toid`)
)
comment='设备表'
collate='utf8_general_ci'
engine=innodb;

像这个设置也是不行的。

原因是mysql会默认为表中的第一个timestamp字段(且设置了not null)隐式设置defaulat current_timestamp。所以说上例那样的设置实际上等同于设置了两个current_timestamp。

分析需求

一个表中,有两个字段,createtime和updatetime。

1 当insert的时候,sql两个字段都不设置,会设置为当前的时间

2 当update的时候,sql中两个字段都不设置,updatetime会变更为当前的时间

这样的需求是做不到的。因为你无法避免在两个字段上设置current_timestamp

解决办法有几个:

1 使用触发器。

当insert和update的时候触发器触发时间设置。

网上有人使用这种方法。当然不怀疑这个方法的可用性。但是对于实际的场景来说,无疑是为了解决小问题,增加了复杂性。

2 将第一个timestamp的default设置为0

表结构如下:

create table `device` (
    `id` int(10) unsigned not null auto_increment,
    `toid` int(10) unsigned not null default '0' comment 'toid',
    `createtime` timestamp not null default 0 comment '创建时间',
    `updatetime` timestamp not null default current_timestamp on update current_timestamp comment '最后更新时间',
    primary key (`id`),
    unique index `toid` (`toid`)
)
comment='设备表'
collate='utf8_general_ci'
engine=innodb;

这样的话,你需要的插入和更新操作变为:

insert into device set toid=11,createtime=null;

update device set toid=22 where id=1;

这里注意的是插入操作的createtime必须设置为null!!

虽然我也觉得这种方法很不爽,但是这样只需要稍微修改insert操作就能为sql语句减负,感觉上还是值得的。这也确实是修改最小又能保证需求的方法了。当然这个方法也能和1方法同时使用,就能起到减少触发器编写数量的效果了。

3 老老实实在sql语句中使用时间戳。

这个是最多人也是最常选择的

表结构上不做过多的设计:

create table `device` (
    `id` int(10) unsigned not null auto_increment,
    `toid` int(10) unsigned not null default '0' comment 'toid',
    `createtime` timestamp not null default current_timestamp comment '创建时间',
    `updatetime` timestamp not null comment '最后更新时间',
    primary key (`id`),
    unique index `toid` (`toid`)
)
comment='设备表'
collate='utf8_general_ci'
engine=innodb;

这样你就需要在插入和update的操作的时候写入具体的时间戳。

insert device set toid=11,createtime=’2012-11-2 10:10:10’,updatetime=’2012-11-2 10:10:10’

update device set toid=22,updatetime=’2012-11-2 10:10:10’ where id=1

其实反观想想,这样做的好处也有一个:current_timestamp是mysql特有的,当数据库从mysql转移到其他数据库的时候,业务逻辑代码是不用修改的。

ps:这三种方法的取舍就完全看你自己的考虑了。顺便说一下,最后,我还是选择第三种方法。

timestamp的变体

1,timestamp default current_timestamp on update current_timestamp

在创建新记录和修改现有记录的时候都对这个数据列刷新

2,timestamp default current_timestamp

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

3,timestamp on update current_timestamp

在创建新记录的时候把这个字段设置为0,以后修改时刷新它

4,timestamp default ‘yyyy-mm-dd hh:mm:ss’ on update current_timestamp

在创建新记录的时候把这个字段设置为给定值,以后修改时刷新它

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

相关文章:

验证码:
移动技术网