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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值