mysql在一个表中存储创建时间和最近更新时间

原文地址:http://blog.sina.com.cn/s/blog_672b419f0101k63f.html



今天写一段程序,在mysql中创建了一张表,其中有两个字段,一个是createdTS用来存储本记录创建时间,一个是modifiedTS用来存储本记录最近更新时间。
create table test(a varchar(3),
createdTS timestamp,
modifiedTS timestamp);

表的创建插入修改删除没有任何问题,但是查询出来的结果却有出入,问题就是createdTS实际显示的是最近更新时间,而modifiedTS显示创建时间。
mysql在一个表中存储创建时间和最近更新时间

这个问题在于----
使用show create table test;查看生成的create语句
CREATE TABLE `test` (
  `a` char(1) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `modified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8

那么调换createdTS和modifiedTS顺序可否,不是很合理。

最后我使用以下解决方案。
create table test(a varchar(3),
     createdTS datetime,
     modifiedTS timestamp);
搞定!!!
在插入的时候这样写
insert into test values('1',current_timestamp,null);
---------------------------------------------------------------
最后---
insert语句可以这样写

mysql> insert into test values('3',current_timestamp,null);
Query OK, 1 row affected (0.03 sec)

mysql> insert into test values('4',now(),null);
Query OK, 1 row affected (0.03 sec)

mysql> update test set a='33' where a='3';
Query OK, 1 row affected (0.10 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> update test set a='44' where a='4';
Query OK, 1 row affected (0.04 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from test;
+------+---------------------+---------------------+
| a    | createdTS           | modifiedTS          |
+------+---------------------+---------------------+
| 11   | 2014-04-10 00:02:25 | 2014-04-10 00:02:43 |
| 22   | 2014-04-10 00:02:27 | 2014-04-10 00:02:48 |
| 33   | 2014-04-10 00:18:34 | 2014-04-10 00:19:19 |
| 44   | 2014-04-10 00:18:46 | 2014-04-10 00:19:28 |
+------+---------------------+---------------------+

猜你喜欢

转载自wangxiaoxu.iteye.com/blog/2251965