How to add “ON update current timestamp” to existing table column

前端 未结 2 433
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 14:22

i have column say ts_activity with datatype timestamp in MYSQL and default value to current timestamp. I want to add on update apply current time stamp to this column value.

相关标签:
2条回答
  • 2021-02-07 14:43

    Try this query -

    ALTER TABLE table_name
      CHANGE COLUMN column_name column_name TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
    

    Note, in the table only one field can be with 'ON UPDATE CURRENT_TIMESTAMP' option.

    0 讨论(0)
  • 2021-02-07 14:48

    Devart's suggestion will work, but I prefer to use MODIFY COLUMN instead of CHANGE COLUMN if I'm not renaming the column.

    I also assume that your ts_activity column is not nullable since you have a default, so I am setting it to NOT NULL, but that's up to you.

    This is the statement I would use:

    ALTER TABLE your_table
      MODIFY COLUMN ts_activity TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
    
    0 讨论(0)
提交回复
热议问题