使用通配符(%%)改善 MySQL 搜索性能?
不,当有前导通配符时,MySQL 不会改善搜索性能,因为 MySQL 无法使用索引。如果你改成‘anyLetter%',就可以使用索引
建议使用带有后缀通配符的语法。语法如下 −
SELECT *FROM yourTableName WHERE yoorColumnName LIKE ‘anyLetter%’;
创建表的查询如下 −
mysql> create table TrailingWildCardDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name Varchar(20), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.71 sec)
现在,你可以使用 insert 命令将一些记录插入表中。查询如下 −
mysql> insert into TrailingWildCardDemo(Name) values('John'); Query OK, 1 row affected (0.13 sec) mysql> insert into TrailingWildCardDemo(Name) values('Johnson'); Query OK, 1 row affected (0.17 sec) mysql> insert into TrailingWildCardDemo(Name) values('Mike'); Query OK, 1 row affected (0.16 sec) mysql> insert into TrailingWildCardDemo(Name) values('Kevin'); Query OK, 1 row affected (0.23 sec) mysql> insert into TrailingWildCardDemo(Name) values('Adam'); Query OK, 1 row affected (0.20 sec) mysql> insert into TrailingWildCardDemo(Name) values('Ethan'); Query OK, 1 row affected (0.16 sec) mysql> insert into TrailingWildCardDemo(Name) values('James'); Query OK, 1 row affected (0.19 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from TrailingWildCardDemo;
输出如下 −
+----+---------+ | Id | Name | +----+---------+ | 1 | John | | 2 | Johnson | | 3 | Mike | | 4 | Kevin | | 5 | Adam | | 6 | Ethan | | 7 | James | +----+---------+ 7 rows in set (0.00 sec)
以下是后缀通配符的查询 −
mysql> select *from TrailingWildCardDemo where Name LIKE 'j%';
输出如下 −
+----+---------+ | Id | Name | +----+---------+ | 1 | John | | 2 | Johnson | | 7 | James | +----+---------+ 3 rows in set (0.00 sec)
广告