> 数据库 > MySQL >

mysql timestamp 类型自动更新

mysql创建表时,如果使用timestamp类型没有指定默认值,它会把第一个使用timestamp的字段默认值设定为CURRENT_TIMESTAMP,如果后面还有其他字段使用timestamp,则指定为‘0000-00-00 00:00:00’,同时Extra列中看到on update CURRENT_TIMESTAMP,注意它会在更新操作时会把该字段时间设置为当前时间,即使你更新时没有指定要更新该字段。例子如下:

create table netingcn(id int(11), ts1 timestamp, ts2 timestamp);

desc netingcn;

+-------+-----------+------+-----+---------------------+-----------------------------+
| Field | Type      | Null | Key | Default             | Extra                       |
+-------+-----------+------+-----+---------------------+-----------------------------+
| id    | int(11)   | YES  |     | NULL                |                             |
| ts1   | timestamp | NO   |     | CURRENT_TIMESTAMP   | on update CURRENT_TIMESTAMP |
| ts2   | timestamp | NO   |     | 0000-00-00 00:00:00 |                             |
+-------+-----------+------+-----+---------------------+-----------------------------+

insert into netingcn(id,ts2) values(1,now());

select * from netingcn;

+------+---------------------+---------------------+
| id   | ts1                 | ts2                 |
+------+---------------------+---------------------+
|    1 | 2012-08-04 22:15:20 | 2012-08-04 22:15:20 |
+------+---------------------+---------------------+

update netingcn set ts2 = '2012-08-01' where id = 1;

select * from netingcn;

+------+---------------------+---------------------+
| id   | ts1                 | ts2                 |
+------+---------------------+---------------------+
|    1 | 2012-08-04 22:15:27 | 2012-08-01 00:00:00 |
+------+---------------------+---------------------+

在上述的例子中插入值时没有ts1,故使用当前的系统时间默认值。当使用更新,此处只是更新了ts2字段,但ts1字段值也发生了变化。所以需要注意extra信息中的提示“on update CURRENT_TIMESTAMP”,如果你想使用timestamp类型又不想让该字段存储的值随着更新而自动更新,那就需要创建表是为该类型的字段显示的指定一个默认值,可以使用CURRENT_TIMESTAMP或0000-00-00 00:00:00。例如:

create table netingcn_1(ts1 timestamp default CURRENT_TIMESTAMP, ts2 timestamp default '0000-00-00 00:00:00');

desc netingcn_1;

+-------+-----------+------+-----+---------------------+-------+
| Field | Type      | Null | Key | Default             | Extra |
+-------+-----------+------+-----+---------------------+-------+
| ts1   | timestamp | NO   |     | CURRENT_TIMESTAMP   |       |
| ts2   | timestamp | NO   |     | 0000-00-00 00:00:00 |       |
+-------+-----------+------+-----+---------------------+-------+


(责任编辑:IT)