
Mysql查询去空格方法汇总
mysql去除字段空格字符
·
目录
3、convert()函数配合trim()函数(解决了我的问题)
一、背景
最近系统线上数据库数据出现一个问题,发现某些字段存在一些异常的首尾空格,不管是使用trim对比还是like查询都查询不到具体的数据;在网上找了一些方法,最后发现一个去“不间断空格”的方法解决了问题,在这里做一下记录和汇总。
二、方法
1、trim()、ltrim()、rtrim()函数
语法:trim(字段) || trim([{BOTH | LEADING | TRAILING} [指定字符] FROM] 字段)
(1)trim()去除字段首尾空白字符,也可以去除指定字符
列子:去除商品零件号左右空格,以及指定字符,打印去除字符后的长度
select
p.parts_num as "零件号(包含首尾各3个空格)",
length(p.parts_num) as "原始长度",
trim(p.parts_num),
length(trim(p.parts_num)) as "去除左右空格后长度",
trim(leading ' 7' from p.parts_num),
length(trim(leading ' 7' from p.parts_num)) as "去除左边字符后长度",
trim(trailing '7 ' from p.parts_num),
length(trim(trailing '7 ' from p.parts_num)) as "去除右边字符后长度"
from
product p
where
p.product_id = "1941573845271945216";
结果:
(2)ltrim()去除左空格
select
p.parts_num as "零件号(包含首尾各3个空格)",
length(p.parts_num) as "原始长度",
ltrim(p.parts_num),
length(ltrim(p.parts_num)) as "去除左空格后长度"
from
product p
where
p.product_id = "1941573845271945216";
结果:
(3)rtrim()去除右空格
select
p.parts_num as "零件号(包含首尾各3个空格)",
length(p.parts_num) as "原始长度",
rtrim(p.parts_num),
length(rtrim(p.parts_num)) as "去除右空格后长度"
from
product p
where
p.product_id = "1941573845271945216";
结果:
2、replace()函数
语法:replace(object,search,replace)
(1)替换字段中指定字符为新字符
select
p.parts_num as "零件号(包含首尾各3个空格)",
length(p.parts_num) as "原始长度",
replace(p.parts_num, ' ', ''),
length(replace(p.parts_num, ' ', '')) as "替换空格后长度",
replace(p.parts_num, '7', '8') as "把7替换成8"
from
product p
where
p.product_id = "1941573845271945216";
结果:
(2)指定去除一下特殊字符
水平制表符:CHAR(9)、换行符:CHAR(10)、回车符:CHAR(13)
REPLACE(REPLACE(REPLACE(p.parts_num, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')
3、convert()函数配合trim()函数(解决了我的问题)
(1)使用convert()先转换一些特殊编码的空格(unicode码位u+00a0的utf-8编码,也称为不间断空格)转换成常规空格(ASCII 中编码为0x20)
-- convert转换,trim去除
select TRIM(convert(0xC2A0 using utf8mb4) FROM p.parts_num);
-- 替换掉字符中的不间断空格
select TRIM(REPLACE(p.parts_num, convert(0xC2A0 using utf8mb4), ' '));
这些特殊空格一般常见于各文本编辑器(word、Excel等,刚好出现问题的业务存在Excel导入数据的场景),想要详细了解看下面推荐的文章。
发现一篇有关各种空格的介绍文章,很全面,推荐一下:你不知道的空格 - 走看看
更多推荐
所有评论(0)