优化简单的JOIN或IN查询

时间:2010-10-07 08:32:54

标签: sql mysql join subquery

我有这个问题:

SELECT DISTINCT id, 
                label 
FROM   bbproduct_cust 
WHERE  CUSTNO IN (SELECT CUSTNO 
                  FROM   customer 
                  WHERE  SLSRPTGRP = '1996') 
       AND DEPTNO = '0' 
ORDER  BY label ASC 

EXPLAIN显示

id  select_type         table           type  possible_keys          key            key_len  ref    rows   Extra                                         
1   PRIMARY             bbproduct_cust  ALL   ind_deptno                                            91834  Using where; Using temporary; Using filesort  
2   DEPENDENT SUBQUERY  customer        ref   PRIMARY,ind_slsrptgrp  ind_slsrptgrp  3        const  4      Using where                                   

需要2-3秒,我需要优化它。

我有哪些选择?

2 个答案:

答案 0 :(得分:1)

使用 INNER JOIN ,而不是 IN 选择

这样的东西
SELECT DISTINCT id, 
                label 
FROM   bbproduct_cust INNER JOIN
        customer ON  bbproduct_cust.CUSTNO = customer.CUSTNO
WHERE  SLSRPTGRP = '1996'
       AND DEPTNO = '0' 
ORDER  BY label ASC

答案 1 :(得分:0)

使用INDEX提高性能。 Click here了解更多详情。

相关问题