mysql的like查询中“-”通配符的干扰以及解决办法

一 问题描述

1.通配符%”是 MySQL 中最常用的通配符,它能代表任何长度的字符串,字符串的长度可以为 0。例如,a%b表示以字母 a 开头,以字母 b 结尾的任意长度的字符串。该字符串可以代表 ab、acb、accb、accrb 等字符串。

2.“_”只能代表单个字符,字符的长度不能为 0。例如,a_b可以代表 acb、adb、aub 等字符串。

3.问题描述:

sql语句中通过like模糊查询“_z”,"_c"结尾的数据,但是不是_c,_z结尾的数据,也查询出来了。

select 
t.device_code deviceGroupNoCode, t.point_code dataPointCode, 
t.total_date totalDate, 
count(point_code) as totalNum, sum(duration_time) durationTime
from (
SELECT LEFT(gl_data_point_code, 7 ) AS device_code,gl_data_point_code, point_code, restore_time, 
case when DATE_FORMAT(ifnull(restore_time,'2022-04-11'),'%Y-%m-%d')!='2022-04-11' then '2022-04-11' else '2022-04-11' end as total_date,
MAX(TIMESTAMPDIFF(second,IF(occurrence_time > concat('2022-04-11',' 00:00:00'),occurrence_time,concat('2022-04-11',' 00:00:00')) ,
IF(restore_time < concat('2022-04-11',' 23:59:59'),restore_time,concat(date_add('2022-04-11',interval 1 day),' 00:00:00')))) duration_time 
FROM iip_acc_warn_information, gl_data_point_mapping 
WHERE occurrence_time <= concat('2022-04-11',' 23:59:59') AND ( restore_time IS NULL OR restore_time >= concat('2022-04-11',' 00:00:00') ) 
AND ( warn_id IN ( SELECT id FROM iip_acc_prod_event_def ) OR (warn_id not IN ( SELECT id FROM iip_acc_prod_event_def ) and STATUS = 1 ) )
and ( gl_data_point_code LIKE '30KYQ10%_C%' or gl_data_point_code LIKE '30KYQ10%_Z%' ) AND data_point_code = point_code GROUP BY point_code, restore_time 
) t GROUP BY device_code, point_code, total_date 

 4.原因分析:

自定义编码中的_C,  _z和mysql自定义的通配符"_",冲突了,gl_data_point_code LIKE '30KYQ10%_C%' or gl_data_point_code LIKE '30KYQ10%_Z%'

可以理解为:30KYQ10% 忽略不看_C,表示在含有单个c,或者单个Z的数据就会被搜索到;并不是按照我们设想的要查找“下划线C”结尾的数据。

这个时候就需要将通配符“_”进行转义,如“\_”,加上“\”进行转义。表示含有“下划线C”才能匹配到。

不加“\”的“_”,则_   表示通配符_

加“\”的“_”,则表示下划线

5.解决办法

mysql怎么转义字符_MySQL的转义字符"\"_半泽和莉娜的博客-CSDN博客

二 案例2

1.表中数据:

 2.查询

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值