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:這三種方法的取舍就完全看你自己的考慮了。順便說一下,最後,我還是選擇第三種方法。