mysql-5.7 – mysql,空格等于空字符串

我花了2个小时来解决我后端的问题.

原因是空字符串等于空格:

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-5.7 – mysql,空格等于空字符串 - 代码日志