MySQL 模糊匹配优化

经典语句

SELECT `column` FROM `table` WHERE `field` like '%keyword%';

看到上述这条语句是不是有一丝丝的熟悉,没错,我也是这么写的 - -。
explain 查看性能

id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE bj index drugName_index 302 25812 11.11 Using where; Using index

下面介绍一下locate:

返回 substr 在 str 中第一次出现的位置,如果 substr 在 str 中不存在,返回值为 0

SELECT 'column' FROM 'table' as t WHERE LOCATE(keyword',t.field)>0;

explain 查看性能

id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE bj index drugName_index 302 25812 100 Using where; Using index

上述对比我们可以看到,其实仅有filtered的差别,
filter的解释是这样子的:这个字段表示存储引擎返回的数据在server层过滤后,剩下多少满足查询的记录数量的比例,注意是百分比,不是具体记录数。
那当然是返回的百分比越大越好,代表数据利用率高。

还有一种like查询方式‘keword%’,限制则是必须以keyword开头

SELECT `column` FROM `table` WHERE `field` like 'keyword%';

explain 查看性能

id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE bj range drugName_index drugName_index 302 60 100 Using where; Using index

我们不难发现他的查询性能是优于上述两种方式的,如果符合keyword开头的情况下则可以采用。

猜你喜欢

转载自www.cnblogs.com/zenan/p/10895144.html