MySQL也有默認值timestamp,但在MySQL中,不只是插入就算是修改也會更新timestamp的值!mysql
不然,在MySQL中要記錄建立日期還得使用datetime 而後使用NOW() 函數完成!
1,TIMESTAMP DEFAULT CURRENT_TIMESTAMP
在建立新記錄的時候把這個字段設置爲當前時間,但之後修改時,再也不刷新它
2,TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在建立新記錄和修改現有記錄的時候都對這個數據列刷新
3,TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
在建立新記錄的時候把這個字段設置爲0,每次更新時記錄更新時間。sql
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:00spa
UPDATE t_test2 set a=4 where a=1; INSERT INTO t_test2(a) values(5);
a cur_time up_time no_def_up_timecode
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:00it
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:00io
問題:test
there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clausedate
SELECT VERSION(); 查看mysql版本,結果爲5.5.30-log;這是一個mysql 5.6.4以前的limitationim
找到的一個解決方案是使用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 ;