MySQL错误TIMESTAMP column with CURRENT_TIMESTAMP的解决方法
在部署程序时遇到的一个问题,MySQL定义举例如下:
CREATETABLE`example`( `id`INTEGERUNSIGNEDNOTNULLAUTO_INCREMENT, `created`TIMESTAMPNOTNULLDEFAULTCURRENT_TIMESTAMP, `lastUpdated`TIMESTAMPNOTNULLONUPDATECURRENT_TIMESTAMP, PRIMARYKEY(`id`) )ENGINE=InnoDB;
这段SQL是我从项目中摘取出来的,在测试机器上一切正常,但是部署到生产机器上MySQL报错:
ERROR1293(HY000):Incorrecttabledefinition;therecanbeonlyoneTIMESTAMPcolumnwithCURRENT_TIMESTAMPinDEFAULTorONUPDATEclause.
意思是只能有一个带CURRENT_TIMESTAMP的timestamp列存在,但是为什么本地测试却没有任何问题呢,本地测试的机器安装的MySQL版本5.6.13,而生产机器上安装的却是5.5版本,搜索网络后得知这两种版本之间对于timestamp处理的区别在于:
在MySQL5.5文档有这么一段话:
OneTIMESTAMPcolumninatablecanhavethecurrenttimestampasthedefaultvalueforinitializingthecolumn,astheauto-updatevalue,orboth.Itisnotpossibletohavethecurrenttimestampbethedefaultvalueforonecolumnandtheauto-updatevalueforanothercolumn.
而在MySQL5.6.5做出了以下改变:
Previously,atmostoneTIMESTAMPcolumnpertablecouldbeautomaticallyinitializedorupdatedtothecurrentdateandtime.Thisrestrictionhasbeenlifted.AnyTIMESTAMPcolumndefinitioncanhaveanycombinationofDEFAULTCURRENT_TIMESTAMPandONUPDATECURRENT_TIMESTAMPclauses.Inaddition,theseclausesnowcanbeusedwithDATETIMEcolumndefinitions.Formoreinformation,seeAutomaticInitializationandUpdatingforTIMESTAMPandDATETIME.
根据网上的解决方案,可以使用触发器来替代一下:
CREATETABLE`example`( `id`INTEGERUNSIGNEDNOTNULLAUTO_INCREMENT, `created`TIMESTAMPNOTNULLDEFAULTCURRENT_TIMESTAMP, `lastUpdated`DATETIMENOTNULL, PRIMARYKEY(`id`) )ENGINE=InnoDB; DROPTRIGGERIFEXISTS`update_example_trigger`; DELIMITER// CREATETRIGGER`update_example_trigger`BEFOREUPDATEON`example` FOREACHROWSETNEW.`lastUpdated`=NOW() // DELIMITER;