Mysql's function to find the length is the length() function and the char_length() function; the length() function can return the length of the string in bytes, and the char_length() function can return the length in characters. The length of the string in units.
Both the char_length function and the length function in MySQL can return the length of the string
mysql> select length('MySQL'), char_length('MySQL'); +-----------------+----------------------+ | length('MySQL') | char_length('MySQL') | +-----------------+----------------------+ | 5 | 5 | +-----------------+----------------------+ 1 row in set (0.01 sec)
The functions of the two functions:
LENGTH() Returns the length of a string in bytes.
CHAR_LENGTH() Returns the length of a string in characters.
Judging from the above example, "MySQL" has a total of 5 characters, and each character should occupy 1 byte.
But Chinese is different. Generally, one Chinese character occupies 2-3 bytes. For example:
GBK character set encoding:
select char_length(‘中国’); // 2个字符 select length(‘中国’); // 4个字节,一个汉字2个字节 select bit_length(‘中国’); // 32位。4*8 = 32
UTF8 character set encoding:
select char_length(‘中国’);// 2个字符 select length(‘中国’); // 6个字节,一个汉字3个字节 select bit_length(‘中国’); // 48位。6*8 = 48
Summary
char_length(str )
The unit of length is characters, a multi-byte character is counted as a single character
It does not matter whether it is Chinese characters, numbers or letters. One character
length(str)
Under utf8 encoding, one Chinese character counts as three characters, and one number or letter counts as one character.
Under other encodings, one Chinese character counts as two characters, and one number or letter counts as one character.
Recommended tutorial: mysql video tutorial
The above is the detailed content of What is the function to find length in mysql?. For more information, please follow other related articles on the PHP Chinese website!