When is a timestamp (auto) updated?

前端 未结 5 1406
慢半拍i
慢半拍i 2020-11-30 22:56

If I have a column in a table of type TIMESTAMP and has as default: CURRENT_TIMESTAMP does this column get updated to the current timestamp if I update the valu

5条回答
  •  悲&欢浪女
    2020-11-30 23:16

    Give the command SHOW CREATE TABLE whatever

    Then look at the table definition.

    It probably has a line like this

    logtime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    

    in it. DEFAULT CURRENT_TIMESTAMP means that any INSERT without an explicit time stamp setting uses the current time. Likewise, ON UPDATE CURRENT_TIMESTAMP means that any update without an explicit timestamp results in an update to the current timestamp value.

    You can control this default behavior when creating your table.

    Or, if the timestamp column wasn't created correctly in the first place, you can change it.

    ALTER TABLE whatevertable
         CHANGE whatevercolumn 
                whatevercolumn TIMESTAMP NOT NULL
                               DEFAULT CURRENT_TIMESTAMP 
                               ON UPDATE CURRENT_TIMESTAMP;
    

    This will cause both INSERT and UPDATE operations on the table automatically to update your timestamp column. If you want to update whatevertable without changing the timestamp, that is,

    To prevent the column from updating when other columns change

    then you need to issue this kind of update.

    UPDATE whatevertable
       SET something = 'newvalue',
           whatevercolumn = whatevercolumn
     WHERE someindex = 'indexvalue'
    

    This works with TIMESTAMP and DATETIME columns. (Prior to MySQL version 5.6.5 it only worked with TIMESTAMPs) When you use TIMESTAMPs, time zones are accounted for: on a correctly configured server machine, those values are always stored in UTC and translated to local time upon retrieval.

提交回复
热议问题