王新阳

wangxinyang

MySQL比like语句更高效的写法

locate(substr, str) 区分大小写

instr( string1, string2 [, start_position [, nth_appearance ] ] )
instr(源字符串, 目标字符串, 起始位置, 匹配序号)


以下网络转载,尚未验证

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

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

四、还要给大家介绍一个新成员,那就是find_in_set

find_in_set(str1,str2) 函数:返回str2中str1所在的位置索引,其中str2必须以","分割开。
FIND_IN_SET语句
mysql> select * from test where find_in_set('name1',name); 

五、当然,还有mysql的全文索引

全文索引:http://dev.mysql.com/doc/refman/5.6/en/fulltext-search.html
2016-05-14
2024-05-04 星期六 农历三月二十六