mysql多個TimeStamp設定

2021-09-06 06:41:06 字數 2685 閱讀 5852

timestamp設定預設值是default current_timestamp

timestamp設定隨著表變化而自動更新是on update 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

解決辦法有幾個:

當insert和update的時候觸發器觸發時間設定。

網上有人使用這種方法。當然不懷疑這個方法的可用性。但是對於實際的場景來說,無疑是為了解決小問題,增加了複雜性。

表結構如下:

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方法同時使用,就能起到減少觸發器編寫數量的效果了。

這個是最多人也是最常選擇的

表結構上不做過多的設計:

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

mysql資料匯入遇到的timestamp型別問題

今天準備把最新的表匯入自己以前的機子上做臨時開發,在資料庫匯入的時候遇到乙個問題 incorrect table definition there can be only one timestamp column with current timestamp in default or on upd...

Oracle中date與timestamp的異同

在oracle中儲存date和時間資訊的話,實際上你有兩種字段資料型別的選擇 9i date資料型別 可以儲存月,年,日,世紀,時,分和秒。度量粒度是秒 以使用to char函式把date資料進行傳統地包裝,達到表示成多種格式的目的 select to char sysdate,mm dd yyyy...

oracle中date和timestamp的區別

如果你想在oracle中儲存date和時間資訊的話,實際上你由兩種字段資料型別的選擇的話,就讓我們看看這兩種資料型別的差別和它們提供了些什麼。date資料型別 這個資料型別我們實在是太熟悉了,當我們需要表示日期和時間的話都會想到date型別。它可以儲存月,年,日,世紀,時,分和秒。它典型地用來表示什...