MySQL 合并索引优化不起作用

标签 mysql query-optimization

我尝试在 MySQL 上模拟合并索引,就像这里所说的 http://dev.mysql.com/doc/refman/5.0/en/index-merge-optimization.html但我不知道为什么我不采用列类型='索引合并'。

这里我有构造表:

    create table hotel(
 index1 int not null,
  nume varchar(100),
  index2 int
);

CREATE UNIQUE INDEX hotel_index1 ON hotel (index1);
CREATE UNIQUE INDEX hotel_index2 ON hotel (index2);

insert into hotel(index1,nume,index2) values (1,'primu',1),
(2,'al2lea',2),(5,'al3lea',4),(4,'al4lea',5);

我确实选择了像现场所说的那样:

explain extended select * from hotel where index1 = 5 or index2 = 4;

解释的结果行是:

    id  select_type table   type    possible_keys                key         key_len    ref     rows    filtered    Extra
    1   SIMPLE      hotel   const   hotel_index1,hotel_index2   (null)      (null)      (null)  4        100        Using where

我对索引做错了什么,它们没有像理论上那样合并?

最佳答案

SQL 优化器在优化方面确实很糟糕。另一种方法是使用unionunion all。完全等价的是:

select h.*
from hotel h
where h.index1 = 5 
union
select h.*
from hotel h
where index2 = 4;

这应该正确使用索引(假设表足够大以利用索引)。

注意:这使用union。如果不需要消除重复项,请使用union all

编辑:

documentation有这样富有洞察力的评论:

The choice between different possible variants of the Index Merge access method and other access methods is based on cost estimates of various available options.

显然,成本估算不会引导优化器做出最佳选择。

关于MySQL 合并索引优化不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29054816/

相关文章:

php - Mysql存储过程的查询优化

mysql - 如果列字段超过 2 个单词,如何在 mysql 中删除?

java - 增加与 mySQL DB 的 Java 连接的客户端数据包大小

php - 如何防止在线酒店预订中的竞争条件

sql - 如何优化复杂查询?

postgresql - 如何准确衡量查询的效率?

php - 使用 PHP 的 mySQL 表中的增量主键

php - 如何按距离对数据库中的php结果进行排序

optimization - Hive连接查询优化

php - 如何提高这个mysql查询的速度