Home > Database > Mysql Tutorial > body text

MySQL中比like语句更高效的写法locatepositioninstrfind_in_set_MySQL

WBOY
Release: 2016-06-01 13:00:09
Original
1078 people have browsed it
你是否一直在寻找比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);

-> 7

速度上这三个比用 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)

Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!