MySQL is not allowing ON UPDATE CURRENT_TIMESTAMP for a DATETIME field

后端 未结 7 1225
情书的邮戳
情书的邮戳 2021-02-12 23:33

I have seen a lot of related questions, but I cannot place my finger on this specific question:

I have a MySQL table with both a TIMESTAMP (for when the field was create

7条回答
  •  孤城傲影
    2021-02-13 00:02

    INSERT and UPDATE date/time automatically

    Works with data type: DATETIME or TIMESTAMP

    Tested on: MySQL 5.6.27-2 and MariaDB 10.1.10


    Stores the current date and time on INSERT

    CREATE TABLE table_demo (
        ...
        `CreatedAt` datetime DEFAULT CURRENT_TIMESTAMP
        ...
    );
    

    Stores the current date and time on INSERT and UPDATE

    CREATE TABLE table_demo (
        ...
        `UpdatedAt` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ... 
    );
    

    Stores the current date and time only on UPDATE

    NOTE: when INSERT, the default value is '0000-00-00 00:00:00'

    CREATE TABLE table_demo (
        ...
        `UpdatedAt` datetime DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP
        ...
    );
    

提交回复
热议问题