MySQL ON UPDATE CURRENT_TIMESTAMP not updating

前端 未结 5 1810
轮回少年
轮回少年 2020-12-24 13:06

I\'ve got a table that looks like this:

CREATE TABLE IF NOT EXISTS `Hosts` (
`id` int(128) NOT NULL AUTO_INCREMENT,
`IP` varchar(15) NOT NULL DEFAULT \'\',
`         


        
5条回答
  •  春和景丽
    2020-12-24 13:34

    Have you tried to use null for that field when updating?

    You could also try setting default value to CURRENT_TIMESTAMP, rather than 0000-00-00 00:00:00.

    Nevertheless, whenever I want to have creation and update time I always use the following:

    ...
    CREATED timestamp NOT NULL default '0000-00-00 00:00:00',
    UPDATED timestamp NOT NULL default now() on update now(),
    ....
    

    I use now(), because is an alias for CURRENT_TIMESTAMP and it is shorter. At the end, table structure gets CURRENT_TIMESTAMP, so don't worry.

    The trick with CREATED field is to remember to use null on both fields for INSERT statements, for UPDATE statements it is not required:

    INSERT INTO mytable (field1, field2, created, updated)
    VALUES ('foo', 'bar', null, null);
    

提交回复
热议问题