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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值