索引MySQL中的依赖子查询

时间:2013-07-19 21:46:08

标签: mysql

我有一个复杂的查询,确实产生了我想要的结果,非常慢。 (比如600秒!)

SELECT * 
FROM   clients 
WHERE  type = 'gold' 
       AND state IN( 'TX', 'WV', 'NV', 'IL' ) 
AND phone not in 
       (
          select phone 
          from clients 
          group by phone
          having count(*) > 1
       )
AND cell not in 
       (
          select cell 
          from clients 
          group by cell
          having count(*) > 1
        )

EXPLAIN SELECT给我:

id, select_type, table,  Possible_keys,  key,  key_len,  ref,  rows,  Extra
1, PRIMARY, clients, ALL, ndxCLients_state,IGA_Count, , , , 128070, Using where
2, DEPENDENT SUBQUERY, clients, ALL, , , , , 128070, Using temporary; Using filesort
3, DEPENDENT SUBQUERY, clients, index, , idx_Cell, 258, , 3, Using index

我正在努力做到这里做什么。我想它试图告诉我,我需要手机领域的索引。使用mysql工作台我索引了手机字段。我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

使用LEFT JOIN通常比INNOT IN

更好
SELECT c.*
FROM clients c
LEFT JOIN (SELECT phone
           FROM clients
           GROUP BY phone
           HAVING COUNT(*) > 1) p
ON c.phone = p.phone
LEFT JOIN (SELECT cell
           FROM clients
           GROUP BY cell
           HAVING COUNT(*) > 1) cl
ON c.cell = p.cell
WHERE p.phone IS NULL AND cl.cell IS NULL
AND type = 'gold'
AND state IN( 'TX', 'WV', 'NV', 'IL' )

确保您在phonecell上拥有索引。它们可能会也可能不会用于JOIN,具体取决于type和/或state上的索引是否更有用,但它们将用于优化GROUP BY中的索引。子查询。