MySQL比like语句更高效的写法locate position instr find_in_set

使用内部函数instr,可代替传统的like方式查询,并且速度更快。

instr函数,第一个参数是字段,第二个参数是要查询的串,返回串的位置,第一个是1,如果没找到就是0.

例如,

select name from tpl_user where 1 and instr(`name`,’jack’);

可查询名字中带jack的名字。

 

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);

-> 7

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

posted @ 2017-03-09 14:57  一万年以前  阅读(5298)  评论(0编辑  收藏  举报