MySQL Query:WHERE NOT IN vs left outer join

时间:2016-07-21 10:40:26

标签: mysql

寻求加快查询速度的方法,下面两者都花了很长时间,超过1秒,请评论如何让它变得更好!

查询1(1.03秒):

SELECT id, Quantity AS poqty, 0 AS outqty
FROM po AS a
WHERE active
AND id NOT 
IN (
SELECT id
FROM po_closed
)

解释结果:

> id    select_type table   type    possible_keys   key key_len ref rows    Extra
> 1 PRIMARY a   ALL NULL    NULL    NULL    NULL    497495  Using where
> 2 SUBQUERY    po_closed   index   id  id  4   NULL    484399  Using index

查询2(1.39秒)

SELECT a.id, Quantity AS poqty, 0 AS outqty
FROM po AS a
LEFT OUTER JOIN po_closed AS b ON a.id = b.id
WHERE a.active
AND b.id IS NULL

解释结果:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  a   ALL NULL    NULL    NULL    NULL    497495  Using where
1   SIMPLE  b   ref id  id  4   a.id    1   Using where; Not exists; Using index

我也试过EXISTS,需要1.8秒。

谢谢,

0 个答案:

没有答案