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 DEFAULT ‘yyyy-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

如上所示,该语句可以读出来以秒为单位的时间戳,然后就可以进行各种比较和运算了

原文地址:https://www.cnblogs.com/albertzhangyu/p/9135029.html