MySQL 中 length() 和 char_length() 的區別?


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() 在字串中給出了相同的結果。length() 函式在應用 Unicode 時給出不同的長度。假設一個列名有 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 個位元組。

更新於: 2020 年 6 月 27 日

910 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.