MySQL45讲之前缀索引

本文介绍了字符串前缀索引的优缺点,以及当字符串的区分度不高时如何建立索引。

[En]

This article introduces the advantages and disadvantages of prefix indexing of strings, and how to build indexes can be considered when the differentiation of strings is not high.

前缀索引

对于像 SELECT * FROM t WHERE email = 'xxxx@163.com'的查询语句,如果不对 email列建立索引,那么将会进行全表扫描。

要为字符串编制索引,可以为整个字符串编制索引,也可以只对前几个字符编制索引。二是所谓的前缀标引。

[En]

To index a string, you can index the entire string or only the first few characters. The second is the so-called prefix indexing.

节省存储空间。如果字符串长度比较长,需要对整个字符串建立索引,那么索引树占用的存储空间时很大的。而如果只是对前一部分字符建立索引,那么可以很好的节省存储空间。

1、 可能会增加扫描行数,影响查询性能。因为整个字符串可能不相同,但是前缀可能是相同的,导致使用前缀索引时,需要更多的回表扫描行。

所以,建立前缀索引前需要找到区分度最高的前缀。可以通过 SELECT COUNT(distinct email(n)) FROM t;计算前缀不同的行数,和表的总行数比较,得到区分度最高的前缀。

2、 索引覆盖失效。比如 SELECT id, email FROM t WHERE email = 'xxx@163.com',可以使用覆盖索引,但因为索引树只有字符串部分数据,必须回表拿数据,即索引覆盖失效。

字符串区分度不高时

对于只有字符串而没有区分整个字符串的等价查询场景,如何构建索引可以考虑?

[En]

For equivalent query scenarios where only strings exist and the whole string is not differentiated, how to build an index can be considered?

1、存储逆序字符串并建立索引。适用于原始字符串前缀的区分度不高,但字符串末尾区分度高的场景,查询语句为 SELECT * FROM t WHERE email = reverse(xxx@163.com)

2、新建立一列,内容为原始字符串的 crc32哈希值,并对哈希值这列建立索引。适用于整个字符串前后部分区分度都不高的场景,查询语句为 SELECT * FROM t WHERE crc_col = crc32('xxx@163.com') and email = 'xxx@163.com'。因为可能发生哈希冲突,所以需要再比较下字符串值。

请注意,前缀索引旨在节省存储空间,但相应地增加了开发转换的复杂性和出错的风险。当存储资源充足时,建议优先使用全字符串索引方式。

[En]

Note that the prefix index is designed to save storage space, but correspondingly increases the complexity of the development transformation and the risk of errors. When the storage resources are sufficient, it is recommended to give priority to the whole string indexing method.

Original: https://www.cnblogs.com/flowers-bloom/p/mysql45-prefix-index.html
Author: flowers-bloom
Title: MySQL45讲之前缀索引

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/508148/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球