我可以优化此查询吗?

时间:2013-04-04 09:21:18

标签: mysql sql query-optimization

这个非常简单的查询需要花费很多时间:

SELECT text, url, docid 
FROM retrieve 
LEFT JOIN citations2 
ON citations2.fromdoc = retrieve.docid 
WHERE citations2.todoc IS NULL 
LIMIT 10;

它有一个带有NULL条件的左连接......这可能是原因吗?我把指数放在各处。

这是慢查询日志:

# Time: 130404  8:00:31
# User@Host: em[em] @ zebra [130.239.162.142]
# Query_time: 27.006579  Lock_time: 0.000019 Rows_sent: 0  Rows_examined: 90682
use em_bg04;
SET timestamp=1365055231;
SELECT text, url, docid FROM retrieve LEFT JOIN citations2 ON citations2.fromdoc =   retrieve.docid WHERE citations2.todoc IS NULL LIMIT 10;

以下是所涉及的表格的示意图,以及大小(继续向下滚动以查看查询的EXPLAIN输出)

Table citations2

Table retrieve

这是EXPLAIN的输出:

enter image description here

所以看来它必须经过整个表......我当然读过this,但我无法理解它。那么,有没有更快地使这个查询?

2 个答案:

答案 0 :(得分:2)

尝试此查询

你正在利用短路,所以如果第一个条件变为假,它就不会去检查第二个条件。

希望它有所帮助...

SELECT 
   text, 
   url, 
   docid 
FROM  
   retrieve 
LEFT JOIN 
   citations2 
ON 
   citations2.todoc IS NULL AND 
   citations2.fromdoc = retrieve.docid 
LIMIT 10;

答案 1 :(得分:1)

Meherzad查询看起来很有希望。但我会将他的查询与新创建的索引结合使用

IDX_FROMDOC_TODOC,其中包含两列。