当前位置:网站首页>mysql查询条件字段值末尾有空格也能查到数据问题
mysql查询条件字段值末尾有空格也能查到数据问题
2022-07-27 22:43:00 【大梦_几千秋】
mysql查询条件字段值末尾有空格也能查到数据问题
1、问题描述
今天在工作中遇到了一个问题,生产环境在调用一个定时任务的时间出现了空指针异常,经过排查发现是mysql查询条件字段值末尾有空格也能查到数据。而map中key是带有空格的值,获取不到就空指针了。这里复现一下
这里我库里有两个姓名相同的人,一个名字后面带有空格,一个名字不带空格。这个1是为了截图看出空格效果加的
SELECT * FROM `student` where studentname = '张伟';
这里是查询字段不带空格的人会把字段最后有空格的人查询出来
这里是查询字段最后带有空格的人
SELECT * FROM `student` where studentname = '张伟 ';
查询结果
2、问题原因
出现这个问题的原因是:如果字段是char或varchar类型,那么在字符串比较的时候MySQL使用PADSPACE校对规则,会忽略字段末尾的空格字符,不管后面是一个空格还是多个
3、问题的解决方法
3.1、从SQL方面解决
- 将比较的值使用BINARY函数转为二进制
SELECT * FROM `student` where studentname = BINARY'张伟';
- 使用length函数进行比较(大批量的数据会影响效率)
SELECT * FROM `student` where studentname = '张伟' and LENGTH(studentname) = LENGTH('张伟');
- 使用like函数
SELECT * FROM `student` where studentname like '张伟';
3.2、从Java方面避免
从Java方面避免的话就是查询的时间字符串入参使用trim()方法去除空格,同时查询出来的结果也要处理掉空格
边栏推荐
猜你喜欢

C language programming | single dog topic explanation

One year anniversary of creation, Chongba young Lang

iperf安装与使用
![[BuildRelease Management]Parabuild](/img/80/11c2b539c217ecd6ba55668d3e71e9.png)
[BuildRelease Management]Parabuild
![Jerry's prompt sound processing when switching devices [chapter]](/img/b3/38f55143b5ca8c3b2059c5f6f1da37.png)
Jerry's prompt sound processing when switching devices [chapter]

Use of postman

110. In depth introduction to sap ui5 fileuploader control - why do you need a hidden iframe

Recommend a Hongmeng instant messaging software "fruit chat", which is a bit awesome!!

Redis缓存穿透击穿和雪崩

Un7.13: how to add, delete, modify and query in vs Code?
随机推荐
Leetcode:1997. the first day after visiting all rooms [jump DP]
Leetcode - find the median of two positively ordered arrays
推荐系统-模型:dssm双塔模型做embedding的召回
【C语言入门】ZZULIOJ 1026-1030
Redis-哨兵模式
Self use drawing bed building tutorial
Operator depth anatomy
oracle分组取最大值
Oracle error: ora-01722 invalid number
Network device hard core technology insider firewall and security gateway (VIII) virtualization artifact (middle)
Safety detection risk
[introduction to C language] zzulioj 1026-1030
Recommend a Hongmeng instant messaging software "fruit chat", which is a bit awesome!!
What is the reason for Chinese garbled code when dataworks transmits data to MySQL
Basic use of calculation attributes
论文赏析[ICLR18]联合句法和词汇学习的神经语言模型
If asynchronous processing is implemented according to the framework
Valued at $36billion! SpaceX, which is about to launch its first manned launch, raised $346million
node-red与TDengine交互
I/O设备的基本概念及分类