Mysql5.5中實現createTime和updateTime自動更新

MySQL 5.5中若是同一表中兩個timestamp列的默認值都設置爲CURRENT_TIMESTAMP,會有如下的錯誤提示:

1293 - Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

有下列的解決方法:

1.建表語句

create table test(
id integer not null auto_increment primary key,
  name varchar(20) not null ,
  created timestamp not null default '0000-00-00 00:00:00',
  updated timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
);
2.插入數據方法(timestamp列爲not null時,設置爲null會自動更新爲當前時間)

mysql> insert into test(name,created) values("litao", null);
mysql> select * from test;

+----+-------+---------------------+---------------------+
| id | name  | created             | updated             |
+----+-------+---------------------+---------------------+
|  1 | litao | 2014-06-15 11:24:27 | 2014-06-15 11:24:27 |
+----+-------+---------------------+---------------------+
1 row in set
3.更新時

mysql> update test set name = 'lt' where id = 1;
mysql> select * from test;
+----+------+---------------------+---------------------+
| id | name | created             | updated             |
+----+------+---------------------+---------------------+
|  1 | lt   | 2014-06-15 11:24:27 | 2014-06-15 11:28:29 |
+----+------+---------------------+---------------------+
1 row in set
相關文章
相關標籤/搜索