今天帮同事处理一个SQL(简化过后的)执行报错:
mysql>selectdate_format('2013-11-19','Y-m-d')>timediff('2013-11-19','2013-11-20'); ERROR1267(HY000):Illegalmixofcollations(utf8_general_ci,COERCIBLE)and(latin1_swedish_ci,NUMERIC)foroperation'>'
乍一看挺莫名其妙的,查了下手册,发现有这么一段:
Thelanguageusedfordayandmonthnamesandabbreviationsiscontrolledbythevalueofthelc_time_namessystemvariable(Section9.7,“MySQLServerLocaleSupport”).
TheDATE_FORMAT()returnsastringwithacharactersetandcollationgivenbycharacter_set_connectionandcollation_connectionsothatitcanreturnmonthandweekdaynamescontainingnon-ASCIIcharacters.
也就是说,DATE_FORMATE()函数返回的结果是带有字符集/校验集属性的,而TIMEDIFF()函数则没有字符集/校验集属性,我们来验证一下:
mysql>setnamesutf8; mysql>selectcharset(date_format('2013-11-19','Y-m-d')),charset(timediff('2013-11-19','2013-11-20')); +--------------------------------------------+-----------------------------------------------+ |charset(date_format('2013-11-19','Y-m-d'))|charset(timediff('2013-11-19','2013-11-20'))| +--------------------------------------------+-----------------------------------------------+ |utf8|binary| +--------------------------------------------+-----------------------------------------------+ mysql>setnamesgb2312; mysql>selectcharset(date_format('2013-11-19','Y-m-d')),charset(timediff('2013-11-19','2013-11-20')); +--------------------------------------------+-----------------------------------------------+ |charset(date_format('2013-11-19','Y-m-d'))|charset(timediff('2013-11-19','2013-11-20'))| +--------------------------------------------+-----------------------------------------------+ |gb2312|binary| +--------------------------------------------+-----------------------------------------------+
可以看到,随着通过SETNAMES修改character_set_connection、collation_connection 值,DATE_FORMAT()函数返回结果的字符集也跟着不一样。在这种情况下,想要正常工作,就需要将结果进行一次字符集转换,例如:
mysql>selectdate_format('2013-11-19','Y-m-d')>convert(timediff('2013-11-19','2013-11-20')usingutf8); +----------------------------------------------------------------------------------------------+ |date_format('2013-11-19','Y-m-d')>convert(timediff('2013-11-19','2013-11-20')usingutf8)| +----------------------------------------------------------------------------------------------+ |1| +----------------------------------------------------------------------------------------------+
就可以了:)
您可能感兴趣的文章:sqlformat()函数的用法及简单实例
关于MySQL的整型数据的内存溢出问题的应对方法
在MySQLDump中使用-w语句进行备份的方法
上述就是数据库技术:MySQL中DATE_FORMATE函数使用时的注意点分享的全部内容,如果对大家有所用处且需要了解更多关于mysql数据库学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/dtteaching/911419.html