更好地使用此 SQL 代码假设在列上应用正确的索引!!
假设常量是来自文本框的输入!!
select ...
from .....
where lower(column) like 'Constant%' or lower(column) like '%Constant%'
优于?
select ...
from .....
where lower(column) like '%Constant%'
在第一个代码中,我尝试使用 like 来匹配“常量”,但使用索引尝试幸运地找到匹配项,稍后我尝试进行完全匹配!!
我只要我的成绩不下降!我的意思是,如果两个查询同时运行,或者查询有时可以获得性能升级,我觉得没问题
我使用 lower 因为我们使用 DEFAULT CHARSET=utf8 COLLATE=utf8_bin
最佳答案
我创建了一个小表格:
create table dotdotdot (
col varchar(20),
othercol int,
key(col)
);
我对与您展示的查询类似的查询进行了解释:
explain select * from dotdotdot where lower(col) = 'value'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: dotdotdot
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1
filtered: 100.00
Extra: Using where
注意 type: ALL
这意味着它不能在 col
上使用索引。通过使用 lower()
函数,我们破坏了 MySQL 使用索引的能力,它不得不求助于表扫描,为每一行计算表达式。随着您的 table 越来越大,这将变得越来越昂贵。
反正也没有必要!在默认排序规则中,字符串比较不区分大小写。因此,除非您故意使用区分大小写的排序规则或二进制排序规则声明您的表,否则跳过 lower()
函数调用同样好,因此您可以使用索引。
例子:
explain select * from dotdotdot where col = 'value'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: dotdotdot
partitions: NULL
type: ref
possible_keys: col
key: col
key_len: 23
ref: const
rows: 1
filtered: 100.00
Extra: NULL
type: ref
表示使用非唯一索引。
还比较了使用通配符进行模式匹配。这也打败了索引的使用,它必须进行表扫描。
explain select * from dotdotdot where col like '%value%'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: dotdotdot
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1
filtered: 100.00
Extra: Using where
像这样使用通配符进行模式匹配是非常低效的!
相反,您需要使用全文索引。
您可能会喜欢我的介绍 Full Text Search Throwdown和这里的视频:https://www.youtube.com/watch?v=-Sa7TvXnQwY
在另一个答案中,您询问使用 OR
是否有帮助。 它没有。
explain select * from dotdotdot where col like 'value%' or col like '%value%'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: dotdotdot
partitions: NULL
type: ALL
possible_keys: col
key: NULL
key_len: NULL
ref: NULL
rows: 1
filtered: 100.00
Extra: Using where
请注意,优化器将 col 索引标识为可能的 键,但最终决定不使用它 (key: NULL
)。
关于MySQL 在 OR 使用索引方面的性能优于 %%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40516996/