【发布时间】:2011-12-22 22:15:03
【问题描述】:
我有一个联系人表,其主键为 id。它还有一个二级索引idx_id_del_user(id,deleted,user_id)。
以下查询使用索引,因此非常快 -
select id
from jts_contacts
where id = '00000402-25c8-7375-e3df-4ec5b66de11d'
and deleted = 0;
0.0098 秒内取出 1 行
但是,当我使用 in 子句时,外部查询会进入全表扫描。我希望它使用主键或 idx_id_del_user。
select *
from jts_contacts FORCE INDEX (idx_id_del_user)
where id in
(select id
from jts_contacts
where id = '00000402-25c8-7375-e3df-4ec5b66de11d')
and deleted = 0
9 秒内取出 1 行
解释计划-
id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
------------------------------------------------------------------------------------
1, 'PRIMARY', 'jts_contacts', 'ALL', '', '', '', '', 1127275, 'Using where'
2, 'DEPENDENT SUBQUERY', 'jts_contacts', 'const', 'PRIMARY,idx_id_del_user', 'PRIMARY', '108', 'const', 1, 'Using index'
此表有 120 万条记录,并且已对该表进行了分析。我在没有 FORCE INDEX 选项的情况下尝试过,但它仍然没有使用索引。关于使这个查询更快的任何建议?
警告:使用联接而不是 in 子句将起作用,但是由于这是从现有产品生成的查询 - 它不能更改为使用联接。
【问题讨论】: