我正在使用我的sql,我想删除表emaleikebusiness_2中的重复行,该表比较另一个名为per2的表中的数据我正在使用的查询
delete
FROM
emaillikebusiness_2
WHERE
emaillikebusiness_2.Email_id
IN (
SELECT
per2.BusinessEmail2
FROM
per2 );
explain语句给出输出
'1', 'PRIMARY', 'emaillikebusiness_2', 'ALL', NULL, NULL, NULL, NULL, '30670', 'Using where'
'2', 'DEPENDENT SUBQUERY', 'per2', 'ALL', 'idx_email2person2', NULL, NULL, NULL, '24710', 'Range checked for each record (index map: 0x1)'
我还在两个表上创建了INDEX,并尝试在单个表上创建索引,但仍然需要很长时间才能执行查询。无论如何,我可以减少查询执行时间
答案 0 :(得分:3)
MySQL倾向于优化WHERE ... IN (SELECT ...)
。改为使用JOIN:
DELETE e.*
FROM emaillikebusiness_2 AS e
JOIN per2 AS p
ON e.Email_id = p.BusinessEmail2
我发现使用IN
时,它会经常对第一个表进行全面扫描,在第二个表的索引中搜索Email_id
,即使第一个表是比第二个大得多。但是通过JOIN,它可以在两个表的索引之间进行更有效的匹配。
答案 1 :(得分:1)
试试这个:
DELETE emaillikebusiness_2.* FROM emaillikebusiness_2
INNER JOIN per2 ON emaillikebusiness_2.Email_id = per2.BusinessEmail2
Because in most cases, Inner Join is significantly faster than IN clause.