模糊查询like优化

原sql语句:select project_ name from project_info where project_name like "%北京%"

1.建立索引(最为有效)

我们都知道,因为索引最左前缀匹配原则,全模糊匹配,sql是不走索引的。

所以采用另一种机制,为project_name建立索引,从索引表中模糊匹配索引值去查询索引值。

原sql语句中我只需要project_name,因此为project_name建立索引,形成“表”,因此只从索引表中取速率更快。

通过explain后查询得到sql语句走的是 index索引查询

如果需要查询多个字段,例如sql

select project_name,project_code from project_info where project_name like "%北京%"

可以建立联合索引,为project_code,project_name建立联合索引,这样依旧从索引表中取需要的字段,速度必然快

从一开始的6.3秒变为0.248秒

2.instr()方法截取字符串

sql:select project_name from project_info where instr(project_name,"北京") >0

instr()相当于截取字符串,用时4.9秒

猜你喜欢

转载自blog.csdn.net/tpwulawula/article/details/86671901