mysql, space 等于空字符串

mysql, space equals empty string

我只花了 2 个小时来解决后端问题。

原因是空字符串等于 space:

SELECT ' ' = '';
-> 1

SELECT STRCMP(' ', '');
-> 0 /* means equal */

有趣的是,

SELECT '' REGEXP '[ ]';
-> 0
SELECT '' REGEXP ' ';
-> 0
SELECT ' ' REGEXP ' ';
-> 1

我可以阻止这种情况吗?是设定吗?

这里的文档中解释了失败的原因 http://dev.mysql.com/doc/refman/5.0/en/char.html:

Values in CHAR and VARCHAR columns are sorted and compared according to the character set collation assigned to the column.

All MySQL collations are of type PADSPACE. This means that all CHAR, VARCHAR, and TEXT values in MySQL are compared without regard to any trailing spaces. “Comparison” in this context does not include the LIKE pattern-matching operator, for which trailing spaces are significant.

解决此问题的一种方法是转换为 BINARY

SELECT BINARY '' = ' ';
0

你也可以使用LIKE:

SELECT '' LIKE ' ';
0

不是普通 MySQL 用户,但我在使用 MariaDB 10.2.9 时也遇到了这个问题。我通过将 VARCHAR 列排序规则从 utf8mb4_unicode_ci 更改为 utf8mb4_unicode_nopad_ci.

解决了这个问题

SELECT '' = ' ' COLLATE utf8mb4_unicode_ci;
结果:1

SELECT '' = ' ' COLLATE utf8mb4_unicode_nopad_ci;
结果:0