(2014-05-07 17:40:04) html
標籤: locateinstrfind_in_set |
分類: MySQL |
你是否一直在尋找比MySQL的LIKE語句更高效的方法的,下面我就爲你介紹幾種。
LIKE語句
SELECT `column` FROM `table` where `condition` like `%keyword%'
事實上,能夠使用 locate(position) 和 instr這兩個函數來代替
1、LOCATE語句
SELECT `column` from `table` where locate(‘keyword’, `condition`)>0
2、或是 locate 的別名 position
POSITION語句
SELECT `column` from `table` where position(‘keyword’ IN `condition`)
3、INSTR語句
SELECT `column` from `table` where instr(`condition`, ‘keyword’ )>0
locate、position 和 instr 的差別只是參數的位置不一樣,同時locate 多一個起始位置的參數外,二者是同樣的。
mysql> SELECT LOCATE(‘bar’, ‘foobarbar’,5);
-> 7
速度上這三個比用 like 稍快了一點。
~~~~~~~~~~~~~~~~~~~~~~~華麗的分割線~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4、還要給你們介紹一個新成員,那就是find_in_set
mysql
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 |+----+------------+