如何在 MySQL 中判断中文字符?

一 引子

在生产环境中,经常会有这样的场景:获得中文数据。那问题就来了,怎么才能匹配出中文字符呢?

本文提供两种方法。

二 演示

2.1 环境

如何在 MySQL 中判断中文字符?

2.2 创建测试表和插入测试数据

如何在 MySQL 中判断中文字符?

三 实现

3.1 方法一 正则表达式

如何在 MySQL 中判断中文字符?

3.2 方法二 length() 和 char_length()

如何在 MySQL 中判断中文字符?

四 总结

方法一中,[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

12.5 String Functions