mysql替代like模糊查询的方法

LIKE语句  

SELECT `column` FROM `table` where `condition` like `%keyword%'  

事实上,可以使用 locate(position) 和 instr 这两个函数来代替  

一、LOCATE语句  

SELECT `column` from `table` where locate(‘keyword’, `condition`)>0  

二、locate 的別名 position  

POSITION语句  

SELECT `column` from `table` where position(‘keyword’ IN `condition`)  

三、INSTR语句  

SELECT `column` from `table` where instr(`condition`, ‘keyword’ )>0  

locate、position 和 instr 的差別只是参数的位置不同,同时locate 多一个起始位置的参数外,两者是一样的。  

mysql> SELECT LOCATE(‘bar’, ‘foobarbar’,5);  

instr(str1,str2)
有两种用法:一种是前面参数写变量,后面写列名;还有就是位置调换。两种有不同的效果,instr(str1,str2)的意思是str2在str1中,如果后面写变量前面写列名,则表示搜出表中所有str1列中值包含str2变量的数据,这时候跟(列名   like  '目标表里')的效果是一样的;
instr还有一个需要注意的地方,就是对该函数返回结果值的判断,不写时默认是判断 "> 0";共有三种可能,每种对应情况如下:
----------------------
instr(title,'name')>0  相当于  title like '%name%' 

instr(title,'name')=1  相当于  title like 'name%' 

instr(title,'name')=0  相当于  title not like '%name%' 

速度上这三个比用 like 稍快了一点。 

猜你喜欢

转载自www.cnblogs.com/alexguoyihao/p/9540450.html