Heim  >  Artikel  >  Datenbank  >  MYSQL设计表时,亟需 两个TIMESTAMP 字段的情况

MYSQL设计表时,亟需 两个TIMESTAMP 字段的情况

WBOY
WBOYOriginal
2016-06-07 16:27:101198Durchsuche

MYSQL设计表时,需要 两个TIMESTAMP 字段的情况 有时候,数据库表有这样的需求,要一个记录创建时间,一个记录修改时间。 理想中的设计是这样的,更新时间的初始值和创建时间一样: CREATE TABLE `test_table` (`id` INT( 10 ) NOT NULL,`create_time` TIMEST

MYSQL设计表时,需要 两个TIMESTAMP 字段的情况

有时候,数据库表有这样的需求,要一个记录创建时间,一个记录修改时间。

理想中的设计是这样的,更新时间的初始值和创建时间一样:
CREATE TABLE `test_table` (
`id` INT( 10 ) NOT NULL,
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE = INNODB;


或者是这样的,更新时间初始值为空,只有在更新的时候才有值:
CREATE TABLE `test_table` (
`id` INT( 10 ) NOT NULL,
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE = INNODB;

这样的建表SQL,是执行不了的,执行时报错,估计这个很多人遇到过吧:
Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause


网上找到个解决方法(只适用于更新时间的初始值和创建时间一样,当然这个也说得过去):
CREATE TABLE `test_table` (
`id` INT( 10 ) NOT NULL,
`create_time` TIMESTAMP NOT NULL DEFAULT 0,
`update_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE = INNODB;


INSERT语句这样写:
INSERT INTO test_table (id, create_time, update_time) VALUES (1, NULL, NULL);


或者这样写(注意,没有写create_time):
INSERT INTO test_table (id, update_time) VALUES (1, NULL);


UPDATE语句正常写法(假设test_table.id可以修改):
UPDATE test_table (id) VALUES (2);


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn