MySQL 选择其他 4 个表中不存在 ID 的记录时查询速度变慢
MySQL query slow when selecting records with id that is absent from 4 other tables
我需要 select 来自 table 的所有记录,其中包含其他四个 table 中不属于 "checked" 的 ID。这是我的查询,有效:
select id, idDate, idInfo, idChecked from aTable
where id not in (select id from aSimilarTable1 where idChecked is not null)
and id not in (select id from aSimilarTable2 where idChecked is not null)
and id not in (select id from aSimilarTable3 where idChecked is not null)
and id not in (select id from aSimilarTable4 where idChecked is not null)
table 随着时间的推移而增长,现在这个查询需要很长时间才能达到 运行(最多几分钟)。 table 的大小如下:
aTable - 1000 条记录
aSimilarTable1、2、3、4 - 50,000 条记录
我将致力于减小 table 的大小。但是,有没有更有效的方法来进行上述查询?
--澄清--
并非 aTable 中的所有 ID 都可能出现在 aSimilarTable1、2、3 或 4 中。我正在寻找 aTable 中不存在于任何 aSimilarTable 中的 ID,或者如果存在,则不是 "checked"。
--更新--
解释查询计划:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY aTable ALL null null null null 796 Using where
5 DEPENDENT SUBQUERY aSimilarTable4 ALL null null null null 21217 Using where
4 DEPENDENT SUBQUERY aSimilarTable3 ALL null null null null 59077 Using where
3 DEPENDENT SUBQUERY aSimilarTable2 ALL null null null null 22936 Using where
2 DEPENDENT SUBQUERY aSimilarTable1 ALL null null null null 49734 Using where
使用 LEFT JOIN
的。
SELECT a.id, a.idDate, a.idInfo, a.idChecked
FROM aTable a
LEFT JOIN aSimilarTable1 b ON a.id = b.id
LEFT JOIN aSimilarTable2 c ON a.id = c.id
LEFT JOIN aSimilarTable3 d ON a.id = d.id
LEFT JOIN aSimilarTable4 e ON a.id = e.id
我需要 select 来自 table 的所有记录,其中包含其他四个 table 中不属于 "checked" 的 ID。这是我的查询,有效:
select id, idDate, idInfo, idChecked from aTable
where id not in (select id from aSimilarTable1 where idChecked is not null)
and id not in (select id from aSimilarTable2 where idChecked is not null)
and id not in (select id from aSimilarTable3 where idChecked is not null)
and id not in (select id from aSimilarTable4 where idChecked is not null)
table 随着时间的推移而增长,现在这个查询需要很长时间才能达到 运行(最多几分钟)。 table 的大小如下:
aTable - 1000 条记录
aSimilarTable1、2、3、4 - 50,000 条记录
我将致力于减小 table 的大小。但是,有没有更有效的方法来进行上述查询?
--澄清--
并非 aTable 中的所有 ID 都可能出现在 aSimilarTable1、2、3 或 4 中。我正在寻找 aTable 中不存在于任何 aSimilarTable 中的 ID,或者如果存在,则不是 "checked"。
--更新--
解释查询计划:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY aTable ALL null null null null 796 Using where
5 DEPENDENT SUBQUERY aSimilarTable4 ALL null null null null 21217 Using where
4 DEPENDENT SUBQUERY aSimilarTable3 ALL null null null null 59077 Using where
3 DEPENDENT SUBQUERY aSimilarTable2 ALL null null null null 22936 Using where
2 DEPENDENT SUBQUERY aSimilarTable1 ALL null null null null 49734 Using where
使用 LEFT JOIN
的。
SELECT a.id, a.idDate, a.idInfo, a.idChecked
FROM aTable a
LEFT JOIN aSimilarTable1 b ON a.id = b.id
LEFT JOIN aSimilarTable2 c ON a.id = c.id
LEFT JOIN aSimilarTable3 d ON a.id = d.id
LEFT JOIN aSimilarTable4 e ON a.id = e.id