尽管更新记录,MySQL中的时间戳仍未更新

时间:2013-02-19 08:39:59

标签: mysql phpmyadmin

我的列中包含MySQL数据库中的时间戳。无论我更新记录多少次,我的时间戳都不会更新。我有什么办法让它自动更新吗?

在Stackoverflow中搜索其他问题,大多数人都说相反,这真的很混乱!例如,这一个,Should I use field 'datetime' or 'timestamp'?(查看最高评分的答案)

谢谢

这是我的表结构

+----------------+-------------+------+-----+-------------------+----------------+
| Field          | Type        | Null | Key | Default           | Extra          |
+----------------+-------------+------+-----+-------------------+----------------+
| Num            | int(11)     | NO   | PRI | NULL              | auto_increment |
| mem_name       | varchar(50) | NO   |     | NULL              |                |
| mem_id         | int(11)     | NO   |     | NULL              |                |
| car_number     | varchar(11) | NO   |     | NULL              |                |
| firstcall_time | timestamp   | NO   |     | CURRENT_TIMESTAMP |                |
| tow_time       | datetime    | NO   |     | NULL              |                |
+----------------+-------------+------+-----+-------------------+----------------+
6 rows in set (0.00 sec)

One Record:

+-----+----------+--------+------------+---------------------+---------------------+
| Num | mem_name | mem_id | car_number | firstcall_time      | tow_time            |
+-----+----------+--------+------------+---------------------+---------------------+
|   1 | Jakey    |  54564 | SHA34345   | 2013-02-19 16:14:12 | 2013-02-19 16:32:45 |
+-----+----------+--------+------------+---------------------+---------------------+
1 row in set (0.00 sec)

After Updating:

+-----+----------+--------+------------+---------------------+---------------------+
| Num | mem_name | mem_id | car_number | firstcall_time      | tow_time            |
+-----+----------+--------+------------+---------------------+---------------------+
|   1 | Tommy    |  54564 | SHA34345   | 2013-02-19 16:14:12 | 2013-02-19 16:32:45 |
+-----+----------+--------+------------+---------------------+---------------------+
1 row in set (0.00 sec)

2 个答案:

答案 0 :(得分:7)

您的时间戳未更新的主要原因是您没有在表创建语句中添加ON UPDATE CURRENT_TIMESTAMP子句。

使用alter table命令更改它并修改列

With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP, 
the column has the current timestamp for its default value and 
is automatically updated to the current timestamp.

您必须添加On UPDATE CURRENT_TIMESTAMP

CREATE TABLE t1 (
  id int, ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            ON UPDATE CURRENT_TIMESTAMP);

编辑 - 表格修改命令

alter table <tablename> modify <columnName> TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP;

参考http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html

答案 1 :(得分:5)

添加On UPDATE CURRENT_TIMESTAMP

MySQL查询:

ALTER TABLE `table_name` CHANGE `date_field` `date_field` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP 

希望它有所帮助!