mysql查询条件字段值末尾有空格也能查到数据问题

mysql查询条件字段值末尾有空格也能查到数据问题

游戏|数码彩彩2024-03-04 7:37:21415A+A-

最近在联调某个业务时发现使用的签名总是验证不过,该业务根据如用户名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 ')

点击这里复制本文地址 版权声明:本文内容由网友提供,该文观点仅代表作者本人。本站(https://www.angyang.net.cn)仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件举报,一经查实,本站将立刻删除。

昂扬百科 © All Rights Reserved.  渝ICP备2023000803号-3网赚杂谈