《MYSQL教程MySQL中DATE_FORMATE函數(shù)使用時的注意點》要點:
本文介紹了MYSQL教程MySQL中DATE_FORMATE函數(shù)使用時的注意點,希望對您有用。如果有疑問,可以聯(lián)系我們。
MYSQL應(yīng)用今天幫同事處理一個SQL(簡化過后的)執(zhí)行報錯:
MYSQL應(yīng)用
mysql> select date_format('2013-11-19','Y-m-d') > timediff('2013-11-19', '2013-11-20');
ERROR 1267 (HY000): Illegal mix of collations (utf8_general_ci,COERCIBLE) and (latin1_swedish_ci,NUMERIC) for operation '>'
MYSQL應(yīng)用乍一看挺莫名其妙的,查了下手冊,發(fā)現(xiàn)有這么一段:
MYSQL應(yīng)用The language used for day and month names and abbreviations is controlled by the value of the lc_time_names system variable (Section 9.7, “MySQL Server Locale Support”).
MYSQL應(yīng)用The DATE_FORMAT() returns a string with a character set and collation given by character_set_connection and collation_connection so that it can return month and weekday names containing non-ASCII characters.
MYSQL應(yīng)用也就是說,DATE_FORMATE() 函數(shù)返回的結(jié)果是帶有字符集/校驗集屬性的,而 TIMEDIFF() 函數(shù)則沒有字符集/校驗集屬性,我們來驗證一下:
MYSQL應(yīng)用
mysql> set names utf8;
mysql> select charset(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> set names gb2312;
mysql> select charset(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 |
+--------------------------------------------+-----------------------------------------------+
MYSQL應(yīng)用可以看到,隨著通過 SET NAMES 修改 character_set_connection、collation_connection? 值,DATE_FORMAT() 函數(shù)返回結(jié)果的字符集也跟著不一樣.在這種情況下,想要正常工作,就需要將結(jié)果進行一次字符集轉(zhuǎn)換,例如:
MYSQL應(yīng)用
mysql> select date_format('2013-11-19','Y-m-d') > convert(timediff('2013-11-19', '2013-11-20') using utf8);
+----------------------------------------------------------------------------------------------+
| date_format('2013-11-19','Y-m-d') > convert(timediff('2013-11-19', '2013-11-20') using utf8) |
+----------------------------------------------------------------------------------------------+
| 1 |
+----------------------------------------------------------------------------------------------+
MYSQL應(yīng)用就可以了 :)
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/3606.html