我有一个复杂的查询,确实产生了我想要的结果,非常慢。 (比如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工作台我索引了手机字段。我在这里缺少什么?
答案 0 :(得分:0)
使用LEFT JOIN通常比IN
和NOT 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
中的索引。子查询。