mysql使用on update current_timestamp注意点最近项目里时间字段(datetime,timestamp)用到了on update current_timestamp属性,自动更新列时间戳。以下记录一些需注意的地方。
先说结论如果你设置了时间随当前时间戳更新( on update current_timestamp),那么当你更新字段时,只有字段值发生变化了,你的时间字段才会变为update操作时的时间。
即没有字段更新时,虽然执行了update语句,也执行成功了,时间字段是不会更新的。
比如我们新建一张表:
create table `t_temp` ( `id` int(11) not null default '0', `username` varchar(255) default null, `upd_time` timestamp null default current_timestamp on update current_timestamp comment '默认取当前时间', primary key (`id`)) engine=innodb default charset=utf8;
然后插入一行数据,然后执行更新。
update t_temp set username = 'mm' where id = 1;
会发现时间列不会更新。
同样,在程序中使用了一些框架,比如tk-mybatis,使用更新方法时(比如int updatebyprimarykeyselective(t record);方法),如果字段没有实际更新,虽然语法执行了,时间字段也不会更新,这点在系统中容易忽视。
current_timestamp()和on update及索引相关基本概率current_timestamp()可以把mysql中timestamp类型设置为当前的时间。
on update个人觉得这个是个神器,一般用于当某个字段是updatetime,最后修改时间的时候,使用这个on update即可。这样就不用开发者自己去处理了,mysql能自动将其处理。
最后来说下索引,这个是来源于百度,具体是谁的,我也忘记了:索引是一种特殊的文件(innodb数据表上的索引是表空间的一个组成部分),它们包含着对数据表里所有记录的引用指针。
可以这样说,数据库索引就像是一本书的目录,它能提高数据库查询的速度。索引分为聚簇索引和非聚簇索引两种,聚簇索引是按照数据存放的物理位置为顺序的,而非聚簇索引就不一样了;聚簇索引能提高多行检索的速度,而非聚簇索引对于单行的检索很快。
如果建立过多的索引,会对更新和插入操作的速度产生影响,因为需要更新每个索引文件。对于一个经常需要更新和插入的表格,就没有必要为一个很少使用的where字句单独建立索引了,对于比较小的表,排序的开销不会很大,也没有必要建立另外的索引。
代码与实例如下建表代码:
create table timedemo( id varchar(64) not null, timetest timestamp not null, primary key (id));
当添加一个新数据的时候:
他会自动创建时间,比如某个订单表,他要记录下订单的时间,就可以使用这种方法进行处理。
包括updatetime,最后更新时间:
create table timedemo2( id varchar(64) not null, createtime timestamp not null default current_timestamp(), updatetime timestamp not null default current_timestamp() on update current_timestamp(), primary key (id) );
//上面这个mysql5.7以上版本不会有问题,但5.7以下版本就会有问题
//5.7以下的版本推荐使用程序去插入。
这里用5.5演示下on update的效果
create table timedemo3( id varchar(64) not null, updatetime timestamp not null default current_timestamp() on update current_timestamp(), primary key (id));
当修改了这个表的某些数据后,updatetime这个数值会自动更新。
每次对这条记录进行更新,updatetime就会自动更新,这样的话,就不用程序员自己去处理了。
这里可以发现,难过很多互联网公司都喜欢用mysql5.7以上的版本,而传统行业还是在用mysql5.5版本。
说下索引key和index
create table timedemo4( id varchar(64) not null, id2 varchar(64) not null, updatetime timestamp not null default current_timestamp() on update current_timestamp(), primary key (id), key(id2))engine=innodb default charset=utf8
普通索引的唯一目的是提高数据访问的速度,这种索引由关键字key或index定义。因此,应该只为那些最经常出现在查询条件(where column = ...)或排序条件(order by column)中的数据列创建索引。
为了创建索引,应选择一个最规整、最紧凑的数据列,如一个整数类型的数据列,只要有可能。
以上就是mysql使用on update current_timestamp问题怎么解决的详细内容。