mysql - 复合关键索引是否可以提高 or 子句的性能

标签 mysql sql query-optimization

我在 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/

相关文章:

php - 为什么不自动创建关系表? (在mysql中)

mysql - 删除 MySQL 中的数百万行

mysql - 需要创建自定义查询

MySQL View 创建

java - 在执行删除操作时,少数字段未经过审核,在保留在数据库中时其值为空

php - 解析错误 : syntax error, C :\wamp64\www\PHP\New\input. php 中的意外文件结尾第 25 行

sql - 想要在单个查询中从多个数据中选择所有提到的数据

mysql - 更好的 MySQL 查询?

sql - sqlite中的逻辑或

php - SQL查询与表上的精确值