MySQL錯誤TIMESTAMP column with CURRENT_TIMESTAMP的解決方法
在部署程序時遇到的一個問題,MySQL定義舉例如下:
CREATE TABLE `example` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`lastUpdated` TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
這段SQL是我從項目中摘取出來的,在測試機器上一切正常,但是部署到生產(chǎn)機器上MySQL報錯:
ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause.
意思是只能有一個帶CURRENT_TIMESTAMP的timestamp列存在,但是為什么本地測試卻沒有任何問題呢,本地測試的機器安裝的MySQL版本5.6.13,而生產(chǎn)機器上安裝的卻是5.5版本,搜索網(wǎng)絡(luò)后得知這兩種版本之間對于timestamp處理的區(qū)別在于:
在MySQL 5.5文檔有這么一段話:
One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.
而在MySQL 5.6.5做出了以下改變:
Previously, at most one TIMESTAMP column per table could be automatically initialized or updated to the current date and time. This restriction has been lifted. Any TIMESTAMP column definition can have any combination of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses. In addition, these clauses now can be used with DATETIME column definitions. For more information, see Automatic Initialization and Updating for TIMESTAMP and DATETIME.
根據(jù)網(wǎng)上的解決方案,可以使用觸發(fā)器來替代一下:
CREATE TABLE `example` (
`id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`lastUpdated` DATETIME NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
DROP TRIGGER IF EXISTS `update_example_trigger`;
DELIMITER //
CREATE TRIGGER `update_example_trigger` BEFORE UPDATE ON `example`
FOR EACH ROW SET NEW.`lastUpdated` = NOW()
//
DELIMITER ;
相關(guān)文章
mysql explain的用法(使用explain優(yōu)化查詢語句)
mysql explain可以幫助你檢查索引和更好的優(yōu)化查詢語句,今天特地學(xué)習(xí)了下mysql explain的用法,需要的朋友可以參考下2017-01-01
Mysql數(shù)據(jù)庫從5.6.28版本升到8.0.11版本部署項目時遇到的問題及解決方法
這篇文章主要介紹了Mysql數(shù)據(jù)庫從5.6.28版本升到8.0.11版本過程中遇到的問題及解決方法,解決辦法有三種,每種方法給大家介紹的都很詳細(xì),感興趣的朋友跟隨腳本之家小編一起學(xué)習(xí)吧2018-05-05
mysql運行net start mysql報服務(wù)名無效的解決辦法
這篇文章主要為大家詳細(xì)介紹了mysql運行net start mysql報服務(wù)名無效的解決辦法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-01-01
解決MySQL數(shù)據(jù)庫鏈接超時報1129錯誤問題
MySQL?為了數(shù)據(jù)庫的安全性默認(rèn)在鏈接中斷或者錯誤時記錄錯誤鏈接的ip?等信息(host_cache),有點像系統(tǒng)的錯誤日志的一種機制,這篇文章主要介紹了MySQL數(shù)據(jù)庫鏈接超時報1129錯誤解決辦法,需要的朋友可以參考下2022-10-10
MySQL中動態(tài)生成SQL語句去掉所有字段的空格的操作方法
在數(shù)據(jù)庫管理過程中,我們常常會遇到需要對表中字段進行清洗和整理的情況,本文將詳細(xì)介紹如何在MySQL中動態(tài)生成SQL語句來去掉所有字段的空格,感興趣的朋友一起看看吧2025-04-04

