MySQL - length() 与 char_length()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1734334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:30:38  来源:igfitidea点击:

MySQL - length() vs char_length()

mysqlstring

提问by Yada

What's the main difference between length()and char_length()?

length()和之间的主要区别是char_length()什么?

I believe it has something to do with binary and non-binary strings. Is there any practical reason to store strings as binary?

我相信它与二进制和非二进制字符串有关。将字符串存储为二进制有什么实际原因吗?

mysql> select length('MySQL'), char_length('MySQL');
+-----------------+----------------------+
| length('MySQL') | char_length('MySQL') |
+-----------------+----------------------+
|               5 |                    5 |
+-----------------+----------------------+
1 row in set (0.01 sec)

回答by Andomar

LENGTH()returns the length of the string measured in bytes.
CHAR_LENGTH()returns the length of the string measured in characters.

LENGTH()返回以字节为单位字符串长度。
CHAR_LENGTH()返回以字符为单位的字符串长度。

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

这与 Unicode 尤其相关,其中大多数字符以两个字节进行编码。或 UTF-8,其中字节数不同。例如:

select length(_utf8 ''), char_length(_utf8 '')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282ACin UTF-8) even though it's only one character.

正如您所看到的,欧元符号占用 3 个字节(它0xE282AC以 UTF-8编码),即使它只有一个字符。

回答by Brent

varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.

varchar(10) 将存储 10 个字符,可能超过 10 个字节。在索引中,它将分配字段的最大长度 - 因此,如果您使用 UTF8-mb4,它将为 10 个字符的字段分配 40 个字节。