Home > Database > Mysql Tutorial > body text

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

WBOY
Release: 2016-06-07 16:27:10
Original
1227 people have browsed it

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;
Copy after login


或者是这样的,更新时间初始值为空,只有在更新的时候才有值:
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;
Copy after login

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


网上找到个解决方法(只适用于更新时间的初始值和创建时间一样,当然这个也说得过去):
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;
Copy after login


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


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


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


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!