mysql - 用于搜索第一列和第三列的 3 列索引?

标签 mysql database indexing

假设我有一个索引(col1、col2、col3),它可以对这些查询启用索引搜索:

WHERE col1 = xxx
WHERE col1 = xxx AND col2 = yyy
WHERE col1 = xxx AND col2 = yyy AND AND col3 = zzz

如果我想搜索

WHERE col2 = yyy AND col3 = zzz
WHERE col3 = zzz

我必须创建这些索引:

(col2, col3)
(col3)

对吗?

但是如果我想通过以下方式搜索,我是否必须创建另一个索引:

WHERE col1 = yyy AND col3 = zzz

我尝试搜索答案,但没有找到有关在索引中搜索非连续列的信息,例如 here .

MySQL 是否使用 (col1, col2, col3) 来实现此目的,还是我必须创建 (col1, col3)?

最佳答案

If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to look up rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3).

MySQL cannot use the index to perform lookups if the columns do not form a leftmost prefix of the index. Suppose that you have the SELECT statements shown here:

SELECT * FROM tbl_name WHERE col1=val1;
SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;

SELECT * FROM tbl_name WHERE col2=val2;
SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3;

If an index exists on (col1, col2, col3), only the first two queries use the index. The third and fourth queries do involve indexed columns, but (col2) and (col2, col3) are not leftmost prefixes of (col1, col2, col3).

也就是说,我已经在 >7,000 行表 (InnoDB) 上测试了一些情况。如示例所示,将列重命名为 col1-3,并仅创建主 ID 索引和多列索引:

Table content

指数:

Index definition

以下解释显示了 col1、2 和 3 的所有组合都使用索引:

enter image description here


enter image description here


enter image description here


因此,一旦索引存在,请随意使用列的任意组合,因为它将用于 power set 中的任何列集。您的专栏。


最后,另一列没有索引,不使用索引:

enter image description here


来源:

关于mysql - 用于搜索第一列和第三列的 3 列索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32881269/

相关文章:

postgresql - 在 postgresql 9.4 的查询中的 where 条件中使用多个 OR 运算符时,使用 pg_trgm 模块的索引不起作用

MySQL 简单查询优化

database - 没有发出启动数据库管理器命令。 SQLSTATE=57019

php - 如何在php中使id升序

mysql - 在 Laravel 5 homestead 工作时访问在 XAMPP 中创建的数据库

mysql - 覆盖索引未显示预期的性能

postgresql - Postgres 中的索引?

php - 保存用户生成的表单创建的查询

mysql - 可以获取表 1 中存在但表 2 中不存在的记录的 SQL 查询

php - 在 phpmyadmin 中查询成功,在 php 中查询失败