插入时间:数据入库时间
更新时间:数据最新修改的时间
默认时间戳timestamp取值范围:’1970-01-01 00:00:01’ UTC 至’2038-01-19 03:14:07’ UTC
MySQL5.6.4及以上版本,时间戳精确到微秒(百万分之一秒)
timestamp(N):0(秒)<=N<=6(微秒),N=3(毫秒)
精度的提高:增大内部存储空间,未改变时间戳类型的取值范围。
时间戳列四种定义:
- timestamp: 字段插入和更新时不会自动设置为当前时间
- timestamp default current_timestamp: 字段仅在插入且未指定值时被设定为当前时间,再更新时且未指定值时不会修改【适合入库字段】
- timestamp on update current_timestamp: 字段在插入且未指定值时被设置为‘0000-00-00 00:00:00’,在更新且未指定值时更新为当前时间【适合更新字段】
- timestamp default current_timestamp on update current_timestamp: 字段在插入或更新时未指定值时,被设置为当前时间
注意:当MySQL参数time_zone=system时,查询timestamp字段会调用系统时区做时区转换,而由于系统时区存在全局锁问题,在多并发大数据量访问时会导致线程上下文频繁切换,CPU使用率暴涨,系统响应变慢设置假死。所以建议将time_zone参数设置为system外的值,如中国地区服务器设置为’+8:00’。
drop table if exists table_timestamp;create table table_timestamp(message_pk bigint not null auto_increment,message_content varchar(99),/* 创建时间不可为空*/CreateTime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' ,/* 更新时间默认为空*/UpdateTime timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间' ,primary key (message_pk));insert into table_timestamp(message_content) values('示例-插入');select * from table_timestamp;update table_timestamp set message_content='示例-插入-更新' where message_pk=1;select * from table_timestamp;-- 简单示例mysql> create table x (a int, b timestamp default current_timestamp);b timestamp default current_timestamp : 该字段记录首次插入时间mysql> create table z(a int ,b timestamp on update current_timestamp);b timestamp on update current_timestamp : 该字段自动更新修改时间
