-1

我有一个复杂的查询,它确实产生了我想要的结果,教唆非常缓慢。(比如 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
        )

解释选择给我:

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 工作台我索引了电话字段。我在这里想念什么?

4

1 回答 1

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' )

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

于 2013-07-19T21:55:10.430 回答