【mysql】自动记录"创建日期"和"更新日期"
MySQL也有默认值timestamp,但在MySQL中,不仅是插入就算是修改也会更新timestamp的值!
否则,在MySQL中要记录创建日期还得使用datetime 然后使用NOW() 函数完成!
1,TIMESTAMP DEFAULT CURRENT_TIMESTAMP
在创建新记录的时候把这个字段设置为当前时间,但以后修改时,不再刷新它
2,TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在创建新记录和修改现有记录的时候都对这个数据列刷新
3,TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在创建新记录的时候把这个字段设置为0,每次更新时记录更新时间。
create TABLE t_test2(
a int,
cur_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
up_time TIMESTAMP Not NULL DEFAULT CURRENT_TIMESTAMP,
no_def_up_time TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
INSERT INTO t_test2(a) values(1);
INSERT INTO t_test2(a) values(2);
INSERT INTO t_test2(a) values(3);
a cur_time up_time no_def_up_time
1 2014-12-04 18:11:31 2014-12-04 18:11:31 0000-00-00 00:00:00
2 2014-12-04 18:11:32 2014-12-04 18:11:32 0000-00-00 00:00:00
3 2014-12-04 18:11:32 2014-12-04 18:11:32 0000-00-00 00:00:00
UPDATE t_test2 set a=4 where a=1;
INSERT INTO t_test2(a) values(5);
a cur_time up_time no_def_up_time
4 |2014-12-04 18:17:37 |2014-12-04 18:11:31 |2014-12-04 18:17:37
2 |2014-12-04 18:11:32 |2014-12-04 18:11:32 |0000-00-00 00:00:00
3 |2014-12-04 18:11:32 |2014-12-04 18:11:32 |0000-00-00 00:00:00
5 |2014-12-04 18:17:37 |2014-12-04 18:17:37 |0000-00-00 00:00:00
SELECT * from t_test2;
a cur_time up_time no_def_up_time
4 2014-12-04 18:17:37 2014-12-04 18:11:31 2014-12-04 18:17:37
2 2014-12-04 18:11:32 2014-12-04 18:11:32 0000-00-00 00:00:00
3 2014-12-04 18:11:32 2014-12-04 18:11:32 0000-00-00 00:00:00
5 2014-12-04 18:17:37 2014-12-04 18:17:37 0000-00-00 00:00:00
问题:
there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause
SELECT VERSION(); 查看mysql版本,结果为5.5.30-log;这是一个mysql 5.6.4之前的limitation
找到的一个解决方案是使用TRIGGER如下
CREATE TABLE `lukuang_road_data_release` (
`data_id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
`data_key` VARCHAR( 40 ) NOT NULL ,
`data_path` VARCHAR( 100 ) NOT NULL ,
`data_type` VARCHAR( 20 ) DEFAULT NULL ,
`data_info` VARCHAR( 200 ) DEFAULT NULL ,
`ctime` DATETIME NOT NULL ,
`mtime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
PRIMARY KEY ( `data_id` ) ,
UNIQUE KEY `key_user` ( `data_key` )
) ENGINE = INNODB AUTO_INCREMENT =34 DEFAULT CHARSET = utf8
DROP TRIGGER IF EXISTS `ctime_trigger`;
DELIMITER //
CREATE TRIGGER `ctime_trigger` BEFORE INSERT ON `lukuang_road_data_release`
FOR EACH ROW SET NEW.`ctime` = NOW()
//
DELIMITER ;
转载于:https://my.oschina.net/u/347414/blog/352249