MySQL使用索引问题

时间:2016-05-11 00:59:27

标签: mysql sql sql-optimization

我有一张大表,有大约700万条记录。 (MySQL)

列就像;

id | atype | textbody | .... 

id是主键,atype是索引

当我跑

select * from tablename where `atype`='doit' 

它使用atype索引。 (表中有170万个doit行)

但是当我运行此查询时

select * from tablename where `atype`='doit' or `atype`='payment'

它没有使用索引。我只是说possible_index是atype。 (表中有168个支付行)

有这种行为的解释吗?

如果我运行此查询;

select * from tablename where `atype`='paymentfailed' or `atype`='payment'

它使用atype索引。

因此,每当我使用' doit'时,它都不会使用atype index

1 个答案:

答案 0 :(得分:0)

MySQL对索引非常挑剔。我认为IN而不是OR更明智:

select *
from tablename
where `atype` in ('doit', 'payment');

如果不起作用,请使用union all

select *
from tablename
where `atype` = 'doit'
union all
select *
from tablename
where `atype` = 'payment';