MySQL中有两个函数用来计算字段的长度:LENGTH()
、CHAR_LENGTH()
。
LENGTH()
函数的定义为(命令为:? LENGTH):
Name: ‘LENGTH’
Description:
Syntax: LENGTH(str)
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.
Examples: mysql> SELECT LENGTH(‘text’);
-> 4
CHAR_LENGTH()
函数的定义为(命令为 ? CHAR_LENGTH):
Name: ‘CHAR_LENGTH’
Description:
Syntax: CHAR_LENGTH(str)
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.
LENGTH()
用来计算字节长度
。而CHAR_LENGTH()
用来计算字符长度
。
用来计算单字节字符
二者无区别:
mysql> SELECT LENGTH("CHINA"), CHAR_LENGTH("CHINA");+-----------------+----------------------+| LENGTH("CHINA") | CHAR_LENGTH("CHINA") |+-----------------+----------------------+|5 |5 |+-----------------+----------------------+
用来计算多字接字符时
区别如下(假设使用的字符集为UTF8,汉字在UTF8中占3字节):
mysql> SELECT LENGTH("中国"), CHAR_LENGTH("中国");;+------------------+-----------------------+| LENGTH("中国") | CHAR_LENGTH("中国") |+------------------+-----------------------+|6 | 2 |+------------------+-----------------------+
CHAR(n)
、VARCHAR(n)
中n的含义:MySQL5.0.3之前都是表示字节数,MySQL5.0.3之后都是表示字符数。