天天看点

mysql多个TimeStamp设置分析需求

timestamp设置默认值是default current_timestamp

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

但是由于

两行设置default current_timestamp是不行的。

还有一点要注意

1

2

3

4

5

6

7

8

9

10

11

<code>create table `device` (</code>

<code>    </code><code>`id` int(10) unsigned not null auto_increment,</code>

<code>    </code><code>`toid` int(10) unsigned not null default</code><code>'0'</code> <code>comment</code><code>'toid'</code><code>,</code>

<code>    </code><code>`createtime` timestamp not null comment</code><code>'创建时间'</code><code>,</code>

<code>    </code><code>`updatetime` timestamp not null default current_timestamp comment</code><code>'最后更新时间'</code><code>,</code>

<code>    </code><code>primary key (`id`),</code>

<code>    </code><code>unique index `toid` (`toid`)</code>

<code>)</code>

<code>comment=</code><code>'设备表'</code>

<code>collate=</code><code>'utf8_general_ci'</code>

<code>engine=innodb;</code>

像这个设置也是不行的。

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

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

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

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

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

解决办法有几个:

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

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

表结构如下:

<code>    </code><code>`createtime` timestamp not null default 0 comment</code><code>'创建时间'</code><code>,</code>

<code>    </code><code>`updatetime` timestamp not null default current_timestamp on update current_timestamp comment</code><code>'最后更新时间'</code><code>,</code>

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

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

update device set toid=22 where id=1;

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

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

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

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

<code>    </code><code>`createtime` timestamp not null default current_timestamp comment</code><code>'创建时间'</code><code>,</code>

<code>    </code><code>`updatetime` timestamp not null comment</code><code>'最后更新时间'</code><code>,</code>

这样你就需要在插入和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:这三种方法的取舍就完全看你自己的考虑了。顺便说一下,最后,我还是选择第三种方法。