One Mysql Table with Multiple TIMESTAMP Columns

后端 未结 3 534
时光取名叫无心
时光取名叫无心 2020-12-02 13:58

I want to have one table with two TIMESTAMP columns. One column to keep track of when the record was created and another to keep track of when it was modified.

相关标签:
3条回答
  • 2020-12-02 14:41

    MySQL allows more than one TIMESTAMP columns in the same table, check this example:

    CREATE TABLE t1 (
      ts1 TIMESTAMP DEFAULT 0,
      ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                    ON UPDATE CURRENT_TIMESTAMP);
    CREATE TABLE t2 (
      ts1 TIMESTAMP NULL,
      ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                    ON UPDATE CURRENT_TIMESTAMP);
    CREATE TABLE t3 (
      ts1 TIMESTAMP NULL DEFAULT 0,
      ts2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                    ON UPDATE CURRENT_TIMESTAMP);
    

    Note that the ts1 TIMESTAMP column is DEFAULT with VALUE 0, and the ts2 TIMESTAMP column is DEFAULT with value CURRENT_TIMESTAMP. More info here http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html

    0 讨论(0)
  • 2020-12-02 14:44

    It's documented in the MySQL docs:

    In addition, you can initialize or update any TIMESTAMP column to the current date and time by assigning it a NULL value, unless it has been defined with the NULL attribute to permit NULL values.

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

    0 讨论(0)
  • 2020-12-02 14:54

    MySQL versions before 5.6.1 would not let two TIMESTAMP columns in the same table, unless as you rightly noted with out defaults and allowing null.

    MySQL 5.6.+ allows two or more TIMESTAMP columns in a table.

    More here: http://shankargopal.blogspot.in/2013/03/mysql-566-timestamp-columns-and-default.html

    0 讨论(0)
提交回复
热议问题