如何在 MySQL 中判斷中文字元?

發表於2015-11-13

一 引子

在生產環境中,經常會有這樣的場景:獲得中文資料。那問題就來了,怎麼才能匹配出中文字元呢?

本文提供兩種方法。

二 演示

2.1 環境

2.2 建立測試表和插入測試資料

建立測試表和插入測試資料。

三 實現

3.1 方法一 正規表示式

3.2 方法二 length() 和 char_length()

四 總結

方法一中,[u0391-uFFE5] 匹配中文以外的字元。

方法二中,當字符集為UTF-8,並且字元為中文時,length()char_length() 兩個方法返回的結果不相同。

參考官方文件:

LENGTH()
Return the length of a string in bytes
Returns the length of the string str, measured in bytes. A multibyte character counts as multiple bytes. This means that for a string containing five 2-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.

CHAR_LENGTH()
Return number of characters in argument
Returns the length of the string str, measured in characters. A multibyte character counts as a single character. This means that for a string containing five 2-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.

五 Ref

相關文章