1、语法

instr(sourceString,destString,start,appearPosition) instr(’源字符串’ , ‘目标字符串’ ,’开始位置’,’第几次出现’)

1.sourceString代表源字符串; destString代表要从源字符串中查找的子串; 2.start代表查找的开始位置,这个参数可选的,默认为1; 3.appearPosition代表想从源字符中查找出第几次出现的destString,这个参数也是可选的, 默认为1 4.如果start的值为负数,则代表从右往左进行查找,但是位置数据仍然从左向右计算。 5.返回值为:查找到的字符串的位置。如果没有查找到,返回0。

2、示例

select instr(‘abcd’,’a’,1,1) from dual; —1

select instr(‘abcd’,’c’) from dual; —3

select instr(‘abcd’,’e’,1,1) from dual; —0

3、适用场景

---应用于模糊查询:instr(字段名/列名, ‘查找字段’)

select code,name,dept,occupation from staff where instr(code, ‘001’)> 0;

---等同于

select code, name, dept, occupation from staff where code like ‘%001%’ ;

---应用于判断包含关系:

select ccn,mas_loc from mas_loc where instr(‘FH,FHH,FHM’,ccn)>0;

---等同于

select ccn,mas_loc from mas_loc where ccn in (‘FH’,’FHH’,’FHM’);

4、举例 instr()可以和if函数或case when 函数搭配再结合一些聚合函数,实现较为复杂的计算;

with temp1 as (

select 'chinese@12$你好' as test_field union all

select '@34$我也好chinese' as test_field union all

select '@56$我不好'

)

select

count(1) cnt_total,

count(if(instr(test_field ,'chinese')>0,1,null )) cnt_1

from

temp1

参考:https://it.cha138.com/mysql/show-103561.html

参考文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: