mysql IN查询问题

时间:2011-08-12 11:30:52

标签: mysql

select docid  from A  where  docid IN ( select distinct(docid) from B)

当我在mysql中执行上述查询时,它需要 33 秒,这对于数据大小来说太长了。

以下是两个表的详细信息。

   Table A :
   | docid       | int(11)  | NO   | PRI | NULL    |       |
   Total number of entries = 500 (all entries are unique)

   Table B:
   | docid       | int(11)  | YES  |     | NULL    |       |
   Total number of entries = 66508
   (number of unique entries are 500)

   mysql version : 5.2

如果我只执行select docid from A,则需要0.00秒, 而select docid from B需要0.07秒。

那么为什么IN查询子查询需要33秒?我做错了吗?

2 个答案:

答案 0 :(得分:6)

IN列表非常大 - 60K条目。你最好使用联接:

select A.docid -- edited - I left out the A. :(
from A
join B on B.docid = A.docid;

这应该非常快速地执行,并且会给你与“IN”查询相同的结果。

答案 1 :(得分:4)

MySQL不能很好地处理IN(子查询)。它每次评估外部查询时执行内部查询,而不是“记住”结果。

因此,你做得更好。

其他RDBMS不执行此操作。