欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mysql多个TimeStamp设置的方法解读

程序员文章站 2023-12-20 18:10:16
timestamp设置默认值是default current_timestamp timestamp设置随着表变化而自动更新是on update current_times...
timestamp设置默认值是default current_timestamp
timestamp设置随着表变化而自动更新是on update current_timestamp

但是由于
一个表中至多只能有一个字段设置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:这三种方法的取舍就完全看你自己的考虑了。顺便说一下,最后,我还是选择第三种方法。

上一篇:

下一篇: