The reason has to do with the optimization of SQL queries. Your first version is evaluating the subquery for each row -- although this has been fixed in more recent versions of MySQL. The second version is creating a temporary table, so this goes much faster.
I would recommend using exists
or join
:
DELETE d FROM domains d
WHERE EXISTS (SELECT 1 FROM domains_groups dg WHERE dg.group_id = 9 AND dg.domain_id = d.id);
Or:
DELETE d
FROM domains d JOIN
domaings_groups dg
ON dg.group_id = 9 AND dg.domain_id = d.id;
I would also recommend an index either domain_groups(domain_id, group_id)
(for the above two versions) or domain_groups(group_id, domain_id)
(for the in
version).