
->id int not null,
->modtime timestamp default current_timestamp on update current_timestamp,
->primary key(id)
->)engine=innodb,default charset=utf8
Query OK, 0 rows affected (0.06 sec)
以下是测试,包括建表时记录时间,插入时记录时间,更新时记录时间:
mysql>insert into timetest(id) values (1),(2),(3)
Query OK, 3 rows affected (0.06 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql>select * from timetest
+----+---------------------+
| id | modtime |
+----+---------------------+
| 1 | 2011-09-21 09:56:24 |
| 2 | 2011-09-21 09:56:24 |
| 3 | 2011-09-21 09:56:24 |
+----+---------------------+
3 rows in set (0.00 sec)
mysql>update timetest set id=10 where id=1
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql>select * from timetest
+----+---------------------+
| id | modtime |
+----+---------------------+
| 2 | 2011-09-21 09:56:24 |
| 3 | 2011-09-21 09:56:24 |
| 10 | 2011-09-21 09:57:15 |
+----+---------------------+
3 rows in set (0.00 sec)
mysql>update timetest set id=4 where id=3
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql>select * from timetest
+----+---------------------+
| id | modtime |
+----+---------------------+
| 2 | 2011-09-21 09:56:24 |
| 4 | 2011-09-21 09:58:10 |
| 10 | 2011-09-21 09:57:15 |
+----+---------------------+
3 rows in set (0.00 sec)
mysql>
我们在向表中插入数据的时候,如果表字段有类似于创建时间的字段,往往需要手动添加,特别的麻烦。我们只需要把时间字段设置成 timestamp 类型,然后把默认值设置为 CURRENT_TIMESTAMP 即可。这样在添加一条新数据的时候,该字段会自动生成当前时间,不需要再手动添加,非常的方便。欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)