我刚刚使用where where条件遇到了我的mysql问题,例如WHERE LEFT(field,4)=“abcd”.我目前正在尝试优化我的查询,我注意到它没有使用我定义的任何索引.我认为LEFT()有可能使用索引而SUBSTRING不是吗? (即在这个问题的答案中提到:MySQL Left() or SUBSTRING()?)
因此,在我的情况下,该字段在表格图像中称为类别CHAR(6).为了测试,我定义了各种指数:
ALTER TABLE image ADD INDEX `cat` (`category`);
ALTER TABLE image ADD INDEX `cat2` (`category(2)`);
ALTER TABLE image ADD INDEX `cat4` (`category(4)`);
和id上的主索引,字段类型的简单索引以及其他列上的一个FULLTEXT,我认为它们并不重要.
虽然我得到了以下结果:
EXPLAIN SELECT * FROM image i0_ WHERE LEFT(category,4)=“0000”LIMIT 0,30
+----+-------------+-------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------------+
| 1 | SIMPLE | i0_ | ALL | NULL | NULL | NULL | NULL | 617359 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+--------+-------------+
解决方法:
请改用LIKE:
SELECT * FROM image i0_ WHERE category LIKE "0000%" LIMIT 0,30
这将允许它使用索引.从manual:
The index also can be used for LIKE comparisons if the argument to LIKE is a constant string that does not start with a wildcard character. For example, the following SELECT statements use indexes:
06001
标签:mysql,indexing
来源: https://codeday.me/bug/20190727/1557622.html