如何优化此删除查询?

时间:2015-01-09 10:09:30

标签: mysql

我正在尝试运行此查询:

delete FROM `customer` where customer_id 
not in (SELECT distinct customer_id FROM `order`);

但这需要很长时间,因为customer表有超过一百万条记录,因此会导致暂停和中断。

我怎样才能让它快速?任何替代方案?

修改

以下是与SELECT相同的EXPLAIN:

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
1   PRIMARY     customer    index   NULL    PRIMARY     4   NULL    127659  Using where; Using index
2   DEPENDENT SUBQUERY  order   ALL     NULL    NULL    NULL    NULL    25141   Using where

2 个答案:

答案 0 :(得分:1)

尝试:

DELETE customer FROM customer t1 LEFT JOIN `order` t2 on t1.customer_id = t2.customer_id WHERE t2.customer_id is null;

答案 1 :(得分:0)

首先,您可以从此DELETE命令中删除DISTINCT。这里没有必要。所以试试这个

delete FROM `customer` where customer_id 
not in (SELECT customer_id FROM `order`);

第二,请使用此重建查询检查执行计划

SELECT customer_id FROM `customer` where customer_id 
not in (SELECT customer_id FROM `order`);

这将显示MySQL如何执行此查询以及发生了什么。