简体   繁体   English

为什么我的查询不使用任何索引?

[英]Why doesn't my query use any index?

Here is my query: 这是我的查询:

select u.*,
       concat(user_fname, ' ', user_lname) like concat(?, '%') `both`,
       user_lname like ? last_name
from users u 
where concat(user_fname, ' ', user_lname) like concat(?, '%')
   or user_lname like concat(?, '%')
order by `both`*2 DESC, last_name

Also I've two indexes: users(user_fname,user_lname) , users(user_lname) . 我还有两个索引: users(user_fname,user_lname)users(user_lname)

And here is the result of EXPLAIN : 这是EXPLAIN的结果:

id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra
1  | SIMPLE      | u     | ALL  | user_lname    | NULL | NULL    | NULL | 9    |  Using where

See? 看到? It doesn't use any index. 它不使用任何索引。 Why? 为什么? and how can I make the query optimal? 以及如何使查询最佳化?

  • Don't hide an indexed column inside a function call ( CONCAT ), 不要在函数调用( CONCAT )中隐藏索引列,
  • OR is deadly for optimization, OR对于优化来说是致命的,
  • A leading wildcard ( % ) makes the index unusable in LIKE , 前导通配符( % )使该索引在LIKE不可用,
  • Since you are fetching all the columns, it is impractical to have a "covering" index. 由于要获取所有列,因此具有“覆盖”索引是不切实际的。
  • In some situations, an index for the ORDER BY can be used instead of for WHERE . 在某些情况下,可以使用ORDER BY的索引代替 WHERE的索引。 But you have a mixture of ASC and DESC, so this is not possible (until version 8.0). 但是您混合使用了ASC和DESC,因此这是不可能的(直到8.0版)。

Plan A: Use a FULLTEXT and MATCH on the the fields. 计划A:在字段上使用FULLTEXT和MATCH。 (There are limitations to FULLTEXT that may make this unusable.) (FULLTEXT的局限性可能使其无法使用。)

Plan B: Have an extra column with the concatenation of the columns and do a single LIKE against it. 计划B:在列之间串联一个额外的列,并对它执行一个LIKE。 (This does not fix all the problems.) (这不能解决所有问题。)

Bottom line: Indexes are very efficient if you live within their constraints. 底线: 如果您在索引的约束范围内, 那么索引将非常有效。 Your query violates so many of the limitations, that I don't think there is any hope for the query; 您的查询违反了许多限制,因此我认为查询没有任何希望。 it must perform a table scan. 它必须执行表扫描。

Caveat: There may be more issues. 警告:可能还有更多问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM