Timestamp without change on update

后端 未结 4 1794
感情败类
感情败类 2020-12-19 11:50

In mysql I have a timestamp with the field name added_on. I created that for a table of leads for a crm. But it\'s getting updated whenever I updat

相关标签:
4条回答
  • 2020-12-19 12:17

    If you want control over the timestamp, just change it to DATETIME and then update it yourself when you want to with added_on=NOW()

    This is what I do to avoid complications, then you can be sure that you have complete control over it, which is also useful for archiving or moving data between tables, because you would not want the timestamp to update itself in this case.

    0 讨论(0)
  • 2020-12-19 12:20

    The first TIMESTAMP of a table, by default has ON UPDATE CURRENT_TIMESTAMP. To prevent this (instead of altering the table afterwards) see the MySQL docs here:

    TIMESTAMP and DATETIME columns have no automatic properties unless they are specified explicitly, with this exception: By default, the first TIMESTAMP column has both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP if neither is specified explicitly. To suppress automatic properties for the first TIMESTAMP column, use one of these strategies:

    1) Enable the explicit_defaults_for_timestamp system variable. If this variable is enabled, the DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses that specify automatic initialization and updating are available, but are not assigned to any TIMESTAMP column unless explicitly included in the column definition.

    2) Alternatively, if explicit_defaults_for_timestamp is disabled (the default), do either of the following:

    2a) Define the column with a DEFAULT clause that specifies a constant default value.

    2b) Specify the NULL attribute. This also causes the column to permit NULL values, which means that you cannot assign the current timestamp by setting the column to NULL. Assigning NULL sets the column to NULL.

    0 讨论(0)
  • 2020-12-19 12:26

    You added a ON UPDATE condition to the column!! To remove this, redefine the column as

    ALTER TABLE `mytable` MODIFY `added_on` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
    

    This will effectively remove the ON UPDATE condition.

    0 讨论(0)
  • 2020-12-19 12:43

    The issue is the ON UPDATE CURRENT_TIMESTAMP. You should be able to undo this behavior with an alter statement like this (not sure what your table name is):

    ALTER TABLE leads MODIFY added_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
    
    0 讨论(0)
提交回复
热议问题