略微加速

略速 - 互联网笔记

MySQL查询条件中字符串包含空格的问题

2020-11-20 leiting (1804阅读)

标签 MySql

问题

最近在联调某个业务时发现使用的签名总是验证不过,在MySQL中查询了该业务的私钥配置和业务侧的配置是一样的,问题就出在SQL查询这里,最后将配置导出到本地发现私钥后面多了一个空格,将空格删除然后签名计算OK。问题是:为什么在DB查询条件中的字符串没有包含空格也可以查到实际包含空格的这条记录呢?

原因

如果字段是char或varchar类型,那么在字符串比较的时候MySQL使用PADSPACE校对规则,会忽略字段末尾的空格字符,若想做到精确匹配可以使用下面几种方法:

方法1:使用like语句;

方法2:使用binary类型,例如,select binary 'a' = 'a   '

方法3:再添加一个length()条件,例如,select col from table where col = 'a   ' and LENGTH(col) = LENGTH('a   ')

官方手册说明(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 CHARVARCHAR, 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. 

在stackoverfolw上也可以找到类似的问题:

MySQL comparison operator, spaces

http://stackoverflow.com/questions/10495692/mysql-comparison-operator-spaces



来源:http://blog.csdn.net/delphiwcdj/article/details/16983993


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3