据我所知,当您使用where aField in (select...)
子查询时,会对表中的每一行进行一次评估,因此这确实是性能上的一大损失。
我建议你使用left join
:
select
f.*
from
(D.frames as f
inner join D.items as i on f.item_id = i.id)
left join (
select f2.item_id
from D2.frames as f2
inner join D2.items as i2 on f2.item_id = i2.id
where i2.primary_type='xxx'
) as a on f.item_id = a.item_id
where a.item_id is null;
作为替代方案,请考虑创建一个临时表并将其分为两步:
-- Step 1. Create the temporary table with the ids you need
drop table if exist temp_myTable;
create temporary table temp_myTable
select f2.item_id
from D2.frames as f2
inner join D2.items as i2 on f2.item_id = i2.id
where i2.primary_type='xxx';
-- Step 2. Add the appropriate indexes
alter temporary table temp_myTable
add primary key (item_id); -- Or add index idx_item_id(item_id)
-- Step 3. Run your query using the newly created temp table
select
f.*
from
(D.frames as f
inner join D.items as i on f.item_id = i.id)
left join temp_myTable as a on f.item_id = a.item_id
where a.item_id is null;
希望这可以帮助