最近在聯調某個業務時發現使用的簽名總是驗證不過,該業務根據如用戶名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 ')