MySQL 中的 length() 与 char_length() 有什么区别?

mysqlmysqli database更新于 2025/1/30 16:44:17

char_length() 可用于显示字符串的长度。让我们看一个例子来获取作为参数包含的字符串的长度。

mysql> select char_length('John');

以下是输出。

+---------------------+
| char_length('John') |
+---------------------+
| 4                   |
+---------------------+
1 row in set (0.00 sec)

length() 函数可用于显示以字节为单位的字符串长度。在许多情况下,字符和字节给出相同的长度。

以下是 length() 的示例

mysql> select length('Tim');

以下是输出。

+---------------------+
| length('Tim')       |
+---------------------+
| 3                   |
+---------------------+
1 row in set (0.00 sec)

length() 和 char_length() 在字符串中给出相同的结果。当使用 Unicode 时,length() 函数给出不同的长度。假设列名有 unicode。在 Unicode 中,每个字符占用 2 个字节。

让我们看一个例子 −

mysql> create table LengthAndCharLengthDemo
-> (
-> FirstName varchar(200),
-> SecondName varchar(255) unicode
-> );
Query OK, 0 rows affected (0.49 sec)

将记录插入表中。

mysql> insert into LengthAndCharLengthDemo values('John','Ritter');
Query OK, 1 row affected (0.22 sec)

借助 select 显示表中的所有记录。

mysql> select *from LengthAndCharLengthDemo;

这是输出。

+-----------+------------+
| FirstName | SecondName |
+-----------+------------+
| John      | Ritter     |
+-----------+------------+
1 row in set (0.00 sec)

让我们获取长度。

mysql> select char_length(FirstName),length(Secondname) from LengthAndCharLengthDemo
-> where FirstName='John' and Secondname='John';

这是输出。

+------------------------+--------------------+
| char_length(FirstName) | length(SecondName) |
+------------------------+--------------------+
| 4                      | 8                  |
+------------------------+--------------------+
1 row in set (0.70 sec)

在上面的输出中,您可以看到 length() 函数由于 unicode 返回 8 个字节,而 char_length() 仅返回 4 个字节。


相关文章


有用资源