0

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

在Stackoverflow这里搜索其他问题,大部分都说反了,真的很迷茫!例如,这个, 我应该使用字段'datetime'还是'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)
4

2 回答 2

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

于 2013-02-19T09:06:41.520 回答
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 

希望能帮助到你 !

于 2013-10-20T13:16:46.400 回答