带有SELECT子查询的DELETE卡住了

时间:2014-12-17 10:58:19

标签: mysql subquery

以下导致mysql卡住的delete语句:

DELETE FROM domains WHERE id IN (SELECT domain_id FROM domains_groups WHERE group_id = 9);

虽然这个做同样的声明有效:

DELETE FROM domains WHERE id IN (select id from (SELECT domain_id as id FROM domains_groups WHERE group_id = 9) a);

任何人都可以解释原因吗?

1 个答案:

答案 0 :(得分:2)

原因与SQL查询的优化有关。您的第一个版本正在评估每行的子查询 - 尽管这已在更新版本的MySQL中得到修复。第二个版本是创建一个临时表,所以这要快得多。

我建议使用existsjoin

DELETE d FROM domains d
    WHERE EXISTS (SELECT 1 FROM domains_groups dg WHERE dg.group_id = 9 AND dg.domain_id  = d.id);

或者:

DELETE d
    FROM domains d JOIN
         domaings_groups dg
         ON dg.group_id = 9 AND dg.domain_id  = d.id;

我还建议使用domain_groups(domain_id, group_id)(对于上述两个版本)或domain_groups(group_id, domain_id)(对于in版本)索引。