我在 MySQL 中有一个包含两列的表
id int(11) unsigned NOT NULL AUTO_INCREMENT,
B varchar(191) CHARACTER SET utf8mb4 DEFAULT NULL,
id 就是 PK。
我需要使用其中之一在查询中进行查找。 (:idList) 中的 id 或 (:bList) 中的 B
如果存在包含这两列的复合索引,该查询会执行得更好吗?
最佳答案
不,不会。
索引可用于查找 leftmost columns in an index 中的值:
MySQL can use multiple-column indexes for queries that test all the columns in the index, or queries that test just the first column, the first two columns, the first three columns, and so on. If you specify the columns in the right order in the index definition, a single composite index can speed up several kinds of queries on the same table.
因此,如果您在 id、B
字段(按此顺序)上有复合索引,则该索引可用于根据其 id
查找值,或 id
和 B
值的组合。但不能用于仅基于 B
查找值。但是,如果出现 or
条件,您需要执行以下操作:仅根据 B
查找值。
如果 or
条件中的两个字段都是索引中最左边的字段,则 MySQL 会尝试执行 index merge optimisation ,因此实际上您最好为这两个字段设置单独的索引。
注意:如果您使用 innodb 表引擎,那么将主键添加到任何多列索引是没有意义的,因为 innodb 会默默地将 PK 添加到每个索引。
关于mysql - 复合关键索引是否可以提高 or 子句的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44503141/