最近在联调某个业务时发现使用的签名总是验证不过,该业务根据如用户名userName后加了空格依然能够根据userName查询到结果。即
select * from user where username = "asdf" 与 select * from user where username = "asdf " 的 效果是一致。
问题是:为什么在DB查询条件中的字符串包含空格也可以查到实际没有包含空格的这条记录呢?
如果字段是char或varchar类型,那么在字符串比较的时候MySQL使用PADSPACE校对规则,会忽略字段末尾的空格字符。
官方手册说明(5.0版本):http://dev.mysql.com/doc/refman/5.0/en/char.html
11.1.6.1. The CHAR and VARCHAR Types
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.
方法1:使用like语句;
select * from table where user like 'abcdefg ';
方法2:使用binary类型;
select * from table where user = BINARY 'abcdefg ';
方法3:再添加一个length()条件;
select col from table where col = 'a ' and LENGTH(col) = LENGTH('a ')