mysql模糊查询优化

2015-01-23 22:03:43 · 作者: · 浏览: 4

首先,对数据库要搜索的字段建立索引(mysql索引不熟悉,可参考这里)。

其次,使用下面的函数来进行模糊查询,如果出现的位置>0,表示包含该字符串。

查询效率比like要高。
如:

table.field like  ‘%AAA%’ 可以改为 locate (‘AAA’ , table.field) > 0

注:locate(substr,str)

用explain查看结果,rows越少越好!

1、用like查询

\

2、用locate查询

可以明显的看到,在此处虽然两者的rows一样,但是filtered的值,用了locate后的值是用like的值的10倍。

注:The filtered column is described in the MySQL manual:

The filtered column indicates an estimated percentage of table rows that will be filtered by the table condition. That is, rows shows the estimated number of rows examined and rows × filtered / 100 shows the number of rows that will be joined with previous tables. This column is displayed if you use EXPLAIN EXTENDED. (New in MySQL 5.1.12)

也就是说,filtered的越高越好