我尝试在 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 优化器在或
优化方面确实很糟糕。另一种方法是使用union
或union 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/