关于MySQL数据类型timestamp的讨论

在项目中用到了timestamp这个类型,该字段本意是用于存储改行记录的创建时间的,实际上这是一个很危险的设置;

mysql官方文档上有这么一段话:

The TIMESTAMP data type provides a type that you can use to automatically mark INSERT or UPDATE operations with the current date and time. If you have multiple TIMESTAMP columns in a table, only the first one is updated automatically. (From MySQL 4.1.2 on, you can specify which TIMESTAMP column updates;

意思大概是timestamp类型会随着insert或update更新而自动更新;

下面实际来测试一个案例:

mysql> create table b(ID int ,Time timestamp);
Query OK, 0 rows affected (0.01 sec)

mysql> insert into b values(1,now());
Query OK, 1 row affected (0.00 sec)

mysql> insert into b values(2,now());
Query OK, 1 row affected (0.01 sec)

-------------------------------------------------

mysql> select * from b;
+------+---------------------+
| ID   | Time                |
+------+---------------------+
|    1 | 2013-07-26 13:56:11 |
|    2 | 2013-07-26 13:57:43 |
+------+---------------------+

------------------------------------------------

mysql> update b  set  id=3 where id=2;

------------------------------------------------

mysql> select * from b;
+------+---------------------+
| ID   | Time                |
+------+---------------------+
|    1 | 2013-07-26 13:56:11 |
|    3 | 2013-07-26 16:35:43 |
+------+---------------------+

可以看出timestamp自动更新了;更多timestamp的信息可以查看mysql官方文档http://dev.mysql.com/doc/refman/4.1/en/timestamp-pre-4-1.html

原文地址:https://www.cnblogs.com/simplelogic/p/3217419.html