目前sql有四种匹配模糊查询模式 % _ [] [^]
% 任意长度表示任意0-n个字符,可匹配任意类型和长度
// sql
select * from table where name like '%三%';
// mybatis
.... where name like concat('%',#{name},'%');
_ 单个
表示任意单个字符----用来限长的
// sql
select * from table where name like '_三_';
// mybatis
.... where name like concat('_',#{name},'_');
[] 单个
表示括号内所有列之内的一个
// sql
select * from table where name like '[张李王]三';
// mybatis
.... where name like '[张李王]'#{name};
##[^] 单个
表示不在括号内的字符
// sql
select * from table where name like '[^张李王]三';
// mybatis
.... where name like '[^张李王]'#{name};
模糊查询优化
对于用like查询会有性能问题,且做模糊会让索引失效,从而全表扫描
优化方法有四种
INSTR(str,substr)
instr(title,‘手册’)>0 相当于 title like ‘%手册%’
instr(title,‘手册’)=1 相当于 title like ‘手册%’
instr(title,‘手册’)=0 相当于 title not like ‘%手册%’
select * from table where INSTR(name, #{keyWords} )
LOCATE(‘查询字段’,‘查询条件’)
LOCATE(substr IN str)
select * from table where LOCATE(#{keyWords} , name )
position( ‘查询条件’ in ‘查询字段’)
POSITION(substr IN str)
select * from table where position(#{keyWords} in name )
FIND_IN_SET(‘查询字段’,‘查询条件’)
FIND_IN_SET(str,strlist)
select * from table where FIND_IN_SET(name , #{keyWords} )
多个字段进行模糊搜索
INSTR(CONCAt(mui.nickname,yui.nickname),#{query}) > 0
注意- mybatis中大于号和小于号都用 > < 代替
- 使用了模糊查询,就得用id动态sql来排除null的情况
- sql中用is表示字段未null的值



