我有这样的查询:
select key, name from localtab where key not in (select key from remotetab);
查询需要很长时间,我不明白为什么。
localtab
是本地表,remotetab
是另一台服务器上的远程表。 key
是一个 int
列,它在两个表中都有一个唯一索引。当我分别查询这两个表时,只需要几秒钟。
最佳答案
链接服务器的性能很糟糕。将您需要的数据获取到本地服务器并在那里完成大部分艰苦的工作和处理,而不是在单个查询中混合使用本地和远程。
选择
remotetab 到临时表中
从 remotetab 中选择 [key] 进入 #remote_made_local
在执行 where 子句过滤时使用#temp 表并使用 exists
而不是 in
以获得更好的性能
select a.[key], a.name from localtab a where not exists(select 1 from #remote_made_local b where b.[key] = a.[key] )
与做
select [key], name from localtab where key not in (select [key] from #remote_made_local)
关于sql-server - 选择不在另一个表中的键需要永远,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63504047/