mysql 进行模糊查询时,可使用内部函数 instr,替代传统的 like 方式,并且速度更快。
instr(field, str) 函数,第一个参数 field 是字段,第二个参数 str 是要查询的串,返回串 str 的位置,没找到就是0
先看以前用like方式的代码:
<select id="queryList" parameterType="com.ccb.inm.system.uass.entity.SysDataGroup" resultMap="SysDataGroupResultMap">
<include refid="selectSysDataGroup"/>
<where>
<if test="dataGroupName != null and dataGroupName != ''">
AND DATA_GROUP_NAME like concat('%', #{dataGroupName}, '%')
</if>
<if test="dataGroupAlias != null and dataGroupAlias != ''">
AND DATA_GROUP_ALIAS like concat('%', #{dataGroupAlias}, '%')
</if>
<if test="enabled != null">
AND ENABLED = #{enabled}
</if>
<if test="beginTime != null"><!-- 开始时间检索 -->
and date_format(CREATE_TIME,'%y%m%d') >= date_format(#{beginTime},'%y%m%d')
</if>
<if test="endTime != null"><!-- 结束时间检索 -->
and date_format(CREATE_TIME,'%y%m%d') <= date_format(#{endTime},'%y%m%d')
</if>
</where>
</select>
这种方式使用mysql并对字段进行模糊搜索时,如果系统对字段的字符没有做到限制,就会经常出现用户输入下划线‘’、百分号‘%’此类通配符进行搜索,如此执行往往会检索到错误的结果集,下滑线‘’会匹配单个任意字符,百分号‘%’会匹配任意个任意字符。
解决方案
一,使用INSTR替换like
INSTR不会识别通配符,只会判断第二个字符串参数在第一个字符串中是否存在。确保此论是有据可依的,上官网。
select * FROM SYS_DATA_GROUP WHERE INSTR(DATA_GROUP_NAME,"%");
二,使用转义字符‘\’
'%'会被转义为‘%’,同理‘_’会被转义为‘_’,在你的编程语言过滤用户输入的值,遇到通配符就在前面填上‘\’
三,使用ESCAPE转义
使用(这个用的不熟,暂且举个例子吧)
示例
这种写法的含义是字符‘/’后面的字符都被当成是普通字符,而不再是通配符,这样的做法回有问题,最后一个‘%’应该是被当做通配符处理才是正确的。