这个问题在sql server ce中很普遍
我对所有字段都有索引。
也是相同的查询,但使用 ID IN(int id 列表)非常快。
我试图将查询更改为 OUTER Join 但这只会让它变得更糟。
那么关于为什么会发生这种情况以及如何解决这个问题的任何提示?
最佳答案
那是因为索引对这种查询没有真正的帮助,所以数据库必须进行全表扫描。如果查询(由于某种原因)比简单的“SELECT * FROM TABLE”慢,请改为执行此操作并过滤程序中不需要的 ID。
编辑:根据您的评论,我知道您使用子查询而不是列表。因此,有三种可能的方法可以做到这一点(希望其中一种更快):
原文:
select * from mytable where id not in (select id from othertable);
备选方案 1:
select * from mytable where not exists
(select 1 from othertable where mytable.id=othertable.id);
备选方案 2:
select * from mytable
minus
select mytable.* from mytable in join othertable on mytable.id=othertable.id;
替代方案3:(丑陋且难以理解,但如果其他一切都失败了......)
select * from mytable
left outer join othertable on (mytable.id=othertable.id)
where othertable.id is null;
关于performance - 为什么 SQL Server ce 中的 Select * FROM Table where ID NOT IN (list of int ids) 查询速度很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3545323/