1

我有以下查询。

SELECT MIN(col1) FROM table1 WHERE id1 IN (SELECT id2 FROM table2)

这会产生大约需要 5 秒的输出。

但是,如果我将查询更改为作为两个单独的查询运行,例如:

SELECT id2 FROM table2
SELECT MIN(col1) FROM table1 WHERE id1 IN (_results_from_first_query_)

然后这会产生大约 0.05 秒的输出。

EXPLAIN 显示以下内容(为可怕的缩进道歉):

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   PRIMARY     table1 ALL  NULL    NULL    NULL    NULL    1107294     Using where
2   DEPENDENT SUBQUERY  table2 eq_ref   PRIMARY     PRIMARY     16  const,func  1   Using index

对比

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  table1  range   PRIMARY,id1     id1     8   NULL    12068   Using where

为什么我使用子查询的查询不使用索引?

此外,如果 table2 中我的一组 ID 的大小超过 650,则在执行 IN(_results_from_first_query_) 示例时,索引也会由于某种原因被删除。为什么是这样?

4

1 回答 1

1

怎么样 ::

在 table1 上为 id1 和 table2 为 id2 创建一个索引,查询应该是::

SELECT MIN(col1) FROM table1 

inner join table2 on id1=id2
于 2012-07-11T10:34:40.453 回答