MySql 替換like 查詢

2021-09-12 05:31:53 字數 1671 閱讀 7502

[b]mysql比like語句更高效的寫法

locate

position

instr

find_in_set[/b]

標籤: locate instr find_in_set 分類: mysql

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

五、當然,還有mysql的全文索引

全文索引:

mysql模糊查詢like優化

使用 like value 不走索引 select column from table where field like keyword 1.可使用 like value 前值匹配,可走索引 select column from table where field like keyword 2.使用...

mysql插入,like模糊查詢

1.insert into 最常用簡單的插入語句,可以有以下兩種用法 insert into tb user id,name,age values 100022 tom 25 只給指定的列賦值 insert into tb user values 100022 tom 25 必須 給所有列賦值 注 ...

mysql 高效模糊查詢 代替like

使用下面的函式來進行模糊查詢,如果出現的位置 0,表示包含該字元串。查詢效率比like要高。如果 table.field like aaa 可以改為 locate aaa table.field 0 locate substr,str position substr in str 返回子串subst...