MySQL CURRENT_TIMESTAMP on create and on update

2019-01-08 08:09发布

I want to define table which will have 2 TIMESTAMP fields, someting like this:

CREATE TABLE `msgs` (
    `id` INT PRIMARY KEY AUTO_INCREMENT,
    `msg` VARCHAR(256),
    `ts_create` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `ts_update` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

How to do this avoiding error:

ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

Point is to keep desired behavior of ts_create and ts_update in table schema.

9条回答
干净又极端
2楼-- · 2019-01-08 08:50

You cannot have two TIMESTAMP column with the same default value of CURRENT_TIMESTAMP on your table. Please refer to this link: http://www.mysqltutorial.org/mysql-timestamp.aspx

查看更多
We Are One
3楼-- · 2019-01-08 08:54

you can try this ts_create TIMESTAMP DEFAULT CURRENT_TIMESTAMP, ts_update TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP

查看更多
你好瞎i
4楼-- · 2019-01-08 08:57

i think it is possible by using below technique

`ts_create` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`ts_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
查看更多
欢心
5楼-- · 2019-01-08 08:58

You are using older MySql version. Update your myqsl to 5.6.5+ it will work.

查看更多
你好瞎i
6楼-- · 2019-01-08 09:09

This is the tiny limitation of Mysql in older version , actually after version 5.6 and later multiple timestamps works...

查看更多
孤傲高冷的网名
7楼-- · 2019-01-08 09:12

I think you maybe want ts_create as datetime (so rename -> dt_create) and only ts_update as timestamp? This will ensure it remains unchanging once set.

My understanding is that datetime is for manually-controlled values, and timestamp's a bit "special" in that MySQL will maintain it for you. In this case, datetime is therefore a good choice for ts_create.

查看更多
登录 后发表回答