参考资料:
[MySQL timestamp自动更新时间分享][1]
[MySQL的timestamp类型自动更新问题][2]
[MySQL 5.7 Reference Manual][3]
CREATE TABLE test
(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL,
createdAt TIMESTAMP,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE test
(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL,
createdAt TIMESTAMP,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
在创建如上两个数据表时,出现了以下问题:
Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
后来发现是我安装的 MySQL 的那个版本(5.5.47)不支持这种语法。
只好换成以下写法:
CREATE TABLE test
(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
createdAt TIMESTAMP
);
换个位置就行了,不过挺奇怪的,为啥这样就行呢?错误提示说的是只能出现一个自动更新或默认当前时间戳的TIMESTAMP字段,但为啥第二种情况不可以呢?换个位置又可以了,真是令人难以捉摸。(好像是当有多个TIMESTAMP类型字段时,第一个出现的TIMESTAMP字段需要设置为当前时间戳或自动更新)
或者就用DATETIME代替TIMESTAMP
CREATE TABLE test
(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
createdAt DATETIME
);
在MySQL的5.7.11版本中,以下几个写法都是可以通过的。这样我们可以充分利用这些特性完成一些需求。
CREATE TABLE test
(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL,
createdAt TIMESTAMP,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE TABLE test
(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL,
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE TABLE test
(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL,
createdAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
updatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);```
[1]:http://www.jb51.net/article/38954.htm
[2]:http://blog.sina.com.cn/s/blog_49a665e10100cb52.html
[3]:http://dev.mysql.com/doc/refman/5.7/en/