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

你是否一直在寻找比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);

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

四、新成员find_in_set

find_in_set(str1,str2) 函数:返回str2中str1所在的位置索引,其中str2必须以","分割开。

表:

mysql> select * from region; 
+----+-------------+ 
| id | name      | 
+----+-------------+ 
| 1  | name1,nam2 | 
| 2  | name1    | 
| 3  | name3     | 
| 4  | name2,name4| 
| 5  | name3,name5| 
+----+-------------+ 
5 rows in set (0.00 sec)

FIND_IN_SET语句

mysql> select * from test where find_in_set('name1',name);
+----+------------+ 
| id | name     | 
+----+------------+ 
| 1  | name1,nam2| 
| 2  | name1   | 
+----+------------+ 
2 rows in set (0.02 sec)
原文地址:https://www.cnblogs.com/yszr/p/8149248.html