子查询性能问题

5

我有一个慢查询

select * from table1 where id NOT IN ( select id from table2 )

这样做会更快吗(不确定是否可行):
select * from table1 where id not in ( select id from table2 where id = table1.id )

或者:

select * from table1 where table1.id NOT EXIST( select id from table2 where table2.id = table1.id )

或者:

select * from table1
left join table2 on table2.id = table1.id
WHERE table2.id is null

还是做其他事情?比如将其拆分为两个查询...
2个回答

8
问题是 - 比较中的字段是否可为空(意思是列值可以为NULL)?
如果它们可为空... 在MySQL中,NOT INNOT EXISTS的表现更佳-请参见this link
如果它们不可为空... LEFT JOIN / IS NULL 的表现更佳 - 请参见this link

有趣,所以这些id不可为空,因此我应该重写查询,使用左连接并使用is null...谢谢! - Mark Steudel
@Mark Steudel:不用谢,但请注意,在任何其他数据库中,“NOT IN”和“NOT EXIST”比“LEFT JOIN / IS NULL”更有效。 - OMG Ponies
这只发生在MySQL数据库上?有趣..为什么会这样? - Mark Steudel
@Mark Steudel:因为它们不是基于相同的代码库。 - OMG Ponies

1
select table1.* from table1 
LEFT JOIN table2 ON table1.id = table2.id
WHERE table2.id IS NULL

目标是摆脱 NOT IN


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接