背景

近期发现系统中某个输入框里如果输入 xxx+空格 的时候会出现异常情况,经过排查发现在调用后端接口时会有两步操作,一是从数据库中查询到的数组中将与 xxx+空格 一致的元素剔除,二是根据 xxx+空格 从数据库中查询对应的明细。

出现异常的原因是在剔除时未能剔除掉对应的元素,也就意味着 xxx+空格 对应的内容在数据库中不存在;但是在查询明细时还是查询到了,顿时感觉很费解,也就衍生出了这篇文章后续的内容。

原因

  • 开发人员在处理前端传过来的字符串时没有执行 trim(),所以导致与数组中元素匹配的时候没有匹配到,也就没能剔除对应的元素,”a”.equals(“a “) 的结果肯定是 false 嘛。

  • mysql 在查询时会忽略掉字符串最后的空格,所以导致 xxx+空格 作为查询条件时和 xxx 为同一效果。

详解

对于第一条原因只能说是开发时疏漏,没什么可说的,我们着重了解下第二条,为什么 mysql 会忽略掉查询条件最后的空格。本文基于 mysql 8.0.28,文章中有些内容是 mysql 8.0 新增的,但主体也适用于 5.x 版本。

在探究之前我们需要准备下使用的数据库,毕竟实践出来的结果才是真实的,首先我们准备一个测试使用的数据库和表,结构如下,字符集和排序规则先选择比较常用的 utf8mb4 和 utf8mb4_unicode_ci,之后在表里插入两条数据:

mysql> desc test;
+--------------+-------------+------+-----+---------+-------+
| field        | type        | null | key | default | extra |
+--------------+-------------+------+-----+---------+-------+
| id           | int         | no   | pri | null    |       |
| name_char    | char(20)    | yes  |     | null    |       |
| name_varchar | varchar(20) | yes  |     | null    |       |
+--------------+-------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
insert into `test` values (1, 'char1', 'varchar1');
insert into `test` values (2, 'char2     ', 'varchar2     ');

char 和 varchar 的区别

首先看一下官方对于 char 类型和 varchar 类型的介绍,以下内容摘自 【11.3.2 the char and varchar types】

the length of a char column is fixed to the length that you declare when you create the table. the length can be any value from 0 to 255. when char values are stored, they are right-padded with spaces to the specified length. when char values are retrieved, trailing spaces are removed unless the pad_char_to_full_length sql mode is enabled.
values in varchar columns are variable-length strings. the length can be specified as a value from 0 to 65,535. the effective maximum length of a varchar is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used.

通过以上我们可以得知以下几部分内容:

  • char 类型长度为 0-255,varchar 类型长度为 0-65535,char 和 varchar 类型的长度其实还会受到内容长度的影响,这里我们不深究。

  • char 类型为定长字段,存储时会向右填充空格至声明的长度;varchar 类型为变长字段,存储时声明的只是可存储的最长内容,实际长度与内容有关。

  • 在 sql mode 中未开启 pad_char_to_full_length 时,char 类型在查询时会在忽略尾部空格(关于 sql mode 的资料请移步 【5.1.11 server sql modes】 ,这里我们不深究)

下面的查询结果中第一行是都没有空格的结果,第二行是都带有 5 个空格的结果,可以看到 char 类型无论带不带空格都只会返回基本的字符。

mysql> select concat("(",name_char,")") name_char, concat("(",name_varchar,")") name_varchar from test;
+-----------+-----------------+
| name_char | name_varchar    |
+-----------+-----------------+
| (char1)   | (varchar1)      |
| (char2)   | (varchar2     ) |
+-----------+-----------------+
2 rows in set (0.01 sec)

第一行好理解,你存进去的时候没带空格,数据库自己填充上了空格,总不能查出来的结果还变了吧;第二行则是入库的时候字符串最后的字符和数据库填充的字符是同一种,查询的时候数据库怎么分得清是你自己填的还是它填的呢,直接一刀切。而 varchar 类型因为不会被填充,所以查询结果中完成的保留下了尾部空格。

varchar 对于尾部空格的处理

上节了解过 char 类型查询时会忽略尾部空格,但是在实际使用中发现 varchar 也有类似的规则,在查看文档时发现有以下一段内容,摘自 【11.3.2 the char and varchar types】

values in char, varchar, and text columns are sorted and compared according to the character set collation assigned to the column.
mysql collations have a pad attribute of pad space, other than unicode collations based on uca 9.0.0 and higher, which have a pad attribute of no pad.

根据这一段描述,我们可以得知 char、varchar 和 text 内容的排序和比较过程受排序规则影响,在 uca 9.0.0 之前 pad 属性默认为 pad space,而之后的默认属性为 no pad。

在官方文档中可以找到以下说明,摘自 【trailing space handling in comparisons】

for nonbinary strings (char, varchar, and text values), the string collation pad attribute determines treatment in comparisons of trailing spaces at the end of strings:

  • for pad space collations, trailing spaces are insignificant in comparisons; strings are compared without regard to trailing spaces.

  • no pad collations treat trailing spaces as significant in comparisons, like any other character.

这一段主要描述 char、varchar 和 text 类型在比较时,如果排序规则的 pad 属性为 pad space 则会忽略尾部空格,no pad 属性则不会,而这正解释了最初的问题。我们通过修改列的排序规则验证以下,首先看一下当前使用 pad space 时的查询结果。

mysql> show full columns from test;
+--------------+-------------+--------------------+------+-----+---------+-------+---------------------------------+---------+
| field        | type        | collation          | null | key | default | extra | privileges                      | comment |
+--------------+-------------+--------------------+------+-----+---------+-------+---------------------------------+---------+
| id           | int         | null               | no   | pri | null    |       | select,insert,update,references |         |
| name_char    | char(20)    | utf8mb4_unicode_ci | yes  |     | null    |       | select,insert,update,references |         |
| name_varchar | varchar(20) | utf8mb4_unicode_ci | yes  |     | null    |       | select,insert,update,references |         |
+--------------+-------------+--------------------+------+-----+---------+-------+---------------------------------+---------+
3 rows in set (0.01 sec)

mysql> select * from test where name_varchar = 'varchar2';
+----+-----------+---------------+
| id | name_char | name_varchar  |
+----+-----------+---------------+
|  2 | char2     | varchar2      |
+----+-----------+---------------+
1 row in set (0.01 sec)

可以看到在 pad space 属性下可以通过 varchar2 查询到 varchar2 ,说明比较时忽略的尾部的空格,我们将 name_varchar 的排序规则切换为 uca 9.0.0 以后版本再来看一下结果。

mysql> alter table test change name_varchar name_varchar varchar(20) character set utf8mb4 collate utf8mb4_0900_ai_ci;
query ok, 0 rows affected (0.05 sec)
records: 0  duplicates: 0  warnings: 0

mysql> show full columns from test;
+--------------+-------------+--------------------+------+-----+---------+-------+---------------------------------+---------+
| field        | type        | collation          | null | key | default | extra | privileges                      | comment |
+--------------+-------------+--------------------+------+-----+---------+-------+---------------------------------+---------+
| id           | int         | null               | no   | pri | null    |       | select,insert,update,references |         |
| name_char    | char(20)    | utf8mb4_unicode_ci | yes  |     | null    |       | select,insert,update,references |         |
| name_varchar | varchar(20) | utf8mb4_0900_ai_ci | yes  |     | null    |       | select,insert,update,references |         |
+--------------+-------------+--------------------+------+-----+---------+-------+---------------------------------+---------+
3 rows in set (0.01 sec)

mysql> select * from test where name_varchar = 'varchar2';
empty set (0.00 sec)

 

与预期一样,切换排序规则后,尾部空格参与比较,已经不能通过 varchar2 查询到 varchar2 了。

确定排序规则的 pad 属性

那接下来的问题是如何判断当前的排序规则是基于 uca 9.0.0 之前还是之后的版本呢?其实在 mysql 8.x 版本中,排序规则保存在 information_schema 库的 collations 表中,可以通过以下语句查询对应的 pad 属性值,例如我们一开始选择的 utf8mb4_unicode_ci。

mysql> select collation_name, pad_attribute from information_schema.collations where collation_name = 'utf8mb4_unicode_ci';
+--------------------+---------------+
| collation_name     | pad_attribute |
+--------------------+---------------+
| utf8mb4_unicode_ci | pad space     |
+--------------------+---------------+
1 row in set (0.00 sec)

除了查询数据库以外,还可以通过排序规则的名称进行区别,在官方文档中有以下一段描述,摘自 【unicode collation algorithm (uca) versions】

mysql implements the xxx_unicode_ci collations according to the unicode collation algorithm (uca) described at http://www.unicode.org/reports/tr10/. the collation uses the version-4.0.0 uca weight keys: http://www.unicode.org/public/uca/4.0.0/allkeys-4.0.0.txt. the xxx_unicode_ci collations have only partial support for the unicode collation algorithm.

unicode collations based on uca versions higher than 4.0.0 include the version in the collation name. examples:

  • utf8mb4_unicode_520_ci is based on uca 5.2.0 weight keys (http://www.unicode.org/public/uca/5.2.0/allkeys.txt),

  • utf8mb4_0900_ai_ci is based on uca 9.0.0 weight keys (http://www.unicode.org/public/uca/9.0.0/allkeys.txt).

可以看出,名称类似 xxx_unicode_ci 的排序规则是基于 uca 4.0.0 的,而 xxx_520_ci 是基于 uca 5.2.0,xxx_0900_ci 是基于 uca 9.0.0 的。通过查询数据库验证,排序规则中包含 0900 字样的 pad 属性均为 no pad,符合以上描述。

需要注意的是 binary 排序规则的 pad 属性为 no pad,这里其实不是个例外,因为 char、varchar 和 text 类型都归类为 nonbinary 。

到此这篇关于mysql varchar 类型尾部空格的文章就介绍到这了,更多相关mysql varchar 类型尾部空格内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!