选择不在另一个 table 中的键需要永远
selecting keys which are not in another table takes forever
我有这样的查询:
select key, name from localtab where key not in (select key from remotetab);
查询时间很长,我不明白为什么。
localtab
是本地 table,remotetab
是另一台服务器中的远程 table。 key
是一个 int
列,它在两个 table 中都有唯一索引。当我分别查询两个 table 时,只需要几秒钟。
链接服务器的性能很差。将您需要的数据获取到本地服务器并在那里完成大部分艰苦的工作和处理,而不是在单个查询中混合使用本地和远程。
select
remotetab 到临时表 table
select [key] into #remote_made_local from remotetab
在执行 where 子句过滤时使用#temp table 并使用 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)
还有一种不用临时表的解决方法
通过使用 left join
而不是 not in (select ...)
,您可以大大加快查询速度。像这样:
select l.key, l.name
from localtab l left join remotetab r on l.key = r.key
where r.key is null ;
我有这样的查询:
select key, name from localtab where key not in (select key from remotetab);
查询时间很长,我不明白为什么。
localtab
是本地 table,remotetab
是另一台服务器中的远程 table。 key
是一个 int
列,它在两个 table 中都有唯一索引。当我分别查询两个 table 时,只需要几秒钟。
链接服务器的性能很差。将您需要的数据获取到本地服务器并在那里完成大部分艰苦的工作和处理,而不是在单个查询中混合使用本地和远程。
select
remotetab 到临时表 table
select [key] into #remote_made_local from remotetab
在执行 where 子句过滤时使用#temp table 并使用 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)
还有一种不用临时表的解决方法
通过使用 left join
而不是 not in (select ...)
,您可以大大加快查询速度。像这样:
select l.key, l.name
from localtab l left join remotetab r on l.key = r.key
where r.key is null ;