mysql更新時間戳 Mysql中時間戳自動更新

2021-10-17 12:55:01 字數 964 閱讀 2908

mysql時間戳字段更新

timestamp是mysql中的時間戳字段,這個字段可以支援自動新增和更新。

1.概述

在我們設計表的時候,考慮將行資料的建立時間和最後更新時間記錄下來是很好的實踐。尤其是可能需要做資料同步或者對資料新鮮度有要求的表。舉些應用場景,更新距上次更新超過2小時的行資料,或者是將乙個月前的訂單資料歸檔等等。我們想把這個的需求丟給資料庫伺服器管理,而不是在應用程式中對每一條語句設定建立時間和最後更新時間字段。在mysql中,這實現起來很容易。我們需要借助於default current_timestamp 和 on update current_timestamp

2.簡單示例

建立測試表

create table `timestamptest` (

`id` int(11) not null auto_increment,

`name` varchar(20) default null,

`create_time` timestamp not null default current_timestamp,

`last_modify_time` timestamp not null default current_timestamp on update current_timestamp,

primary key (`id`)

) engine=innodb default charset=utf8

檢測預設值,插入測試資料

insert into timestamptest (name) values ('aa'),('bb'),('cc');

檢測自動更新,更新某條資料

update timestamptest set name = 'ab' where id = 1;

3.實驗結果

MySQL 自動插入 更新時間戳

在 mysql 中,要做到自動出入當前時間戳,只要在定義 時將字段的預設值設定為current timestamp 即可。如 create table if not exists my table creation date datetime default current timestamp ot...

mysql更新時間 Mysql 更新時間

mysql時間加減函式為date add date sub 定義和用法 date add 函式向日期新增指定的時間間隔。date sub 函式向日期減少指定的時間間隔。語法date add date,interval expr type date sub date,interval expr typ...

mysql時間戳儲存

利用時間戳來區分資料庫中的兩條不同資料時,時間衝突是乙個簡單而又麻煩的東西,不管是高併發還是低請求的系統,時間衝突的概率依然存在,只是高低的問題。一般而言,對於時間衝突概率高的系統,一般是提高時間的精度來區分兩條資料,甚至加上如隨機數 程序id 伺服器id等。使用mysql資料庫時,可以利用mysq...