在MySQL中为BINARY LIKE操作建立索引
作者:互联网
我知道varchar_pattern_ops存在于Postgresql中,用于在LIKE查询中进行基于索引的快速搜索,但是MySQL是否有类似的功能?
目前,我有一个Django-MySQL设置,其中有此查询,该查询在未索引字段上运行并具有BINARY LIKE操作,并且需要一分钟才能完成.
我的查询是从文本开头-text%进行部分搜索.
这是表结构.该表实际上包含20多个字段,但是我仅包含主键和要搜索的字段
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------------+---------------+------+-----+--
| id | varchar(255) | NO | PRI | NULL | |
| mid | varchar(255) | NO | MUL | NULL | |
这是查询-
select count(*) from table where mid binary like 'text%';
这些是索引-
PRIMARY KEY index has cardinality 102820460
mid index has cardinality 756032
解决方法:
做一个事实,即MySQL索引字符串的左侧.
如果查询使用通配符右侧,则字符串列可以使用索引:
SELECT * FROM your_table WHERE field LIKE "text%" # can use an index
但请记住,对于索引,限制为767个字节
从Mysql DOC
A B-tree index can be used for column comparisons in expressions that
use the =, >, >=, <, <=, or BETWEEN operators. 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.
https://dev.mysql.com/doc/refman/8.0/en/index-btree-hash.html
标签:mysql,database-indexes 来源: https://codeday.me/bug/20191011/1896326.html