插入时间:数据入库时间
    更新时间:数据最新修改的时间
    默认时间戳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’。

    1. drop table if exists table_timestamp;
    2. create table table_timestamp
    3. (
    4. message_pk bigint not null auto_increment,
    5. message_content varchar(99),
    6. /* 创建时间不可为空*/
    7. CreateTime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' ,
    8. /* 更新时间默认为空*/
    9. UpdateTime timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间' ,
    10. primary key (message_pk)
    11. );
    12. insert into table_timestamp(message_content) values('示例-插入');
    13. select * from table_timestamp;
    14. update table_timestamp set message_content='示例-插入-更新' where message_pk=1;
    15. select * from table_timestamp;
    16. -- 简单示例
    17. mysql> create table x (a int, b timestamp default current_timestamp);
    18. b timestamp default current_timestamp : 该字段记录首次插入时间
    19. mysql> create table z(a int ,b timestamp on update current_timestamp);
    20. b timestamp on update current_timestamp : 该字段自动更新修改时间