您好,欢迎访问一九零五行业门户网

MySQL中同时存在创建和上次更新时间戳字段解决方法浅析

在写这篇文章之前,明确我的mysql版本。 mysqlgt; select version();+------------+| version() |+------------+| 5.5.29-log
在写这篇文章之前,明确我的mysql版本。
mysql> select version();
+------------+
| version()  |
+------------+
| 5.5.29-log |
+------------+
1 row in set (0.00 sec)
现在有这样的需求,一张表中有一个字段created_at记录创建该条记录的时间戳,,另一个字段updated_at记录更新该条记录的时间戳。
我们尝试以下几个语句。
第一个,测试通过。
 create table temp
(
 id int(11) primary key auto_increment,
 name varchar(10),
 updated_at timestamp null default current_timestamp on update current_timestamp
);
第二个,测试不通过。报error 1293 (hy000)错误。(完整错误信息:error 1293 (hy000): incorrect table definition; there can be only one timestamp column with current_timestamp in default or on update clause)
create table temp
(
 id int(11) primary key auto_increment,
 name varchar(10),
 created_at timestamp null default current_timestamp,
 updated_at timestamp null default current_timestamp on update current_timestamp
);
mysql 5.5.29中有这样的奇葩限制,不明白为什么。既然有这样的限制,那么只有绕道而行,现在尝试给出如下几种解决办法。
第一种,created_at使用default current_timestamp或者default now(),updated_at使用触发器。
具体解决方法如下:
1.temp表结构如下:
create table temp
(
 id int(11) primary key auto_increment,
 name varchar(10),
 created_at timestamp null default current_timestamp,
 updated_at timestamp null
);
2.插入测试数据:
3.在temp上创建触发器,实现更新时记录更新时间;
delimiter |
drop trigger if exists tri_temp_updated_at;
create trigger tri_temp_updated_at before update on temp
for each row
begin
 set new.updated_at = now();
end;
|
delimiter ;
4.测试。
 更多详情见请继续阅读下一页的精彩内容:
其它类似信息

推荐信息