MYSQL timestamp用法
来源:互联网 发布:php 数组key长度限制 编辑:程序博客网 时间:2024/06/01 09:48
问题来源
在业务系统中,有时候想要知道用户最后一次活动距离现在的时间。记得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
如上所示,该语句可以读出来以秒为单位的时间戳,然后就可以进行各种比较和运算了。
0 0
- mysql timestamp 基本用法
- MYSQL timestamp用法
- mysql之TIMESTAMP(时间戳)用法详解
- mysql中timestamp(时间戳)的用法
- mysql timestamp
- mysql timestamp
- TIMESTAMP mysql
- mysql timestamp
- mysql timestamp
- mysql TIMESTAMP
- mysql之TIMESTAMP(时间戳)用法详解
- mysql之TIMESTAMP(时间戳)用法详解
- mysql之TIMESTAMP(时间戳)用法详解
- mysql之TIMESTAMP(时间戳)用法详解(转载)
- mysql之TIMESTAMP(时间戳)用法详解
- TIMESTAMP时间戳在mysql的不同用法
- mysql之TIMESTAMP(时间戳)用法详解
- mysql之TIMESTAMP(时间戳)用法详解
- AlarmManager 简介
- 观察者模式
- sharesdk appid
- boost
- 编程技巧及bug解决
- MYSQL timestamp用法
- Android中BuildConfig类的那些事<一>
- 【GOF23设计模式】_模板方法模式_钩子函数_方法回调_好莱坞原则JAVA249
- 学习记录2--mac系统下的类似putty远程操作树莓
- Codeforces 577 B Modulo Sum 简单数学+dp
- 4-11 求自定类型元素序列的中位数 (25分)
- 习题 6-14 UVA - 12118 Inspector's Dilemma 检察员的难题 (DFS 构造欧拉通路)
- 我的经验:指针和指针的引用
- nodejs基于async waterfall/retry的出错重试流程设计