MYSQL timestamp用法

問題來源

在業務系統中,有時候想要知道用戶最後一次活動距離現在的時間。記得mysql是有這樣的字段的,可以直接在一條記錄更新時,自動更新時間。上網查了查,找到了,是timestamp類型。

用法

在表中定義一個timestamp類型的字段,如下所示:

create table test(
    id integer primary key auto_increment,
    name varchar(256) not null,
    createdAt timestamp default current_timestamp on update current_timestamp
);

createdAt字段被定義爲timestamp類型,而且默認值是當前時間戳,當記錄發生更新時,該字段同時會更新爲當前時間戳。timestamp等於是提供了對一條對數據自身修改時間的記錄。
依據不同的場景,一般timestamp會有幾類用法:

在記錄創建修改時都刷新

參見上面的例子,在sql語句上,要同時註明default字段和on update字段。

createdAt timestamp default current_timestamp on update current_timestamp

只在記錄創建時刷新時間,以後修改時不再刷新

如下所示,在定義字段時刪去on update語句。

createdAt timestamp default current_timestamp

在創建時將字段設置爲0,以後修改時刷新

只有on update語句。

createdAt timestamp on update current_timestamp

在創建時給一個定值,修改時刷新

只有on update語句。

createdAt timestamp DEFAULTyyyy-mm-dd hh:mm:ss' on update current_timestamp

這樣,在記錄發生變化時,可以根據需要記錄時間戳。

字段更新值和原值一樣的情況

假定我們更新了表的某個字段,例如name屬性,createdAt也可以相應刷新。但是有一種情況例外,就是如果更新值和原值一樣,mysql出於優化考慮,並不會執行任何操作。此時,爲了記錄時間,可以強制刷新時間戳。

update table test set name = '<new name>', createdAt = current_timestamp where id = 1;

讀取時間戳

如果要讀出時間戳,又該怎麼使用呢?

select unix_timestamp(createdAt) as tt from test

如上所示,該語句可以讀出來以秒爲單位的時間戳,然後就可以進行各種比較和運算了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章