存在()条件下的性能问题

问题描述:

我有一个简单的SQL查询(见下文),长期运行下去(我无法等待其完成)存在()条件下的性能问题

if exists(
    select 1 
    from [files].[Contacts_Migration_Template] c 
    where not exists(select 1 
        from [files].[Additional_Contact_Migration_Template] 
        where contact = c.[migration id]) 
) print 'warning message' 

但子查询(如果存在(子查询)打印 '警告信息')本身是立即执行(见下面的截图)

“全” 查询 enter image description here

子查询 enter image description here

产生的预估执行计划(见下文)两个查询表明,子查询必须比“完全”查询更高查询成本......其中,正如我上面说的,第一(子查询)立即运行,第二个( “全”)无限长的运行...

enter image description here

这是怎么回事?


原始查询

enter image description here

+0

快一个使用哈希联接,只扫描'Additional_Contact_Migration_Template'一次。慢速扫描它(或至少是一个假脱机复制)多次。统计信息是否最新? – 2013-05-09 08:28:13

+0

,但为什么第一个相对查询的成本是83%(对比17%),如果它更快? – 2013-05-09 08:31:08

+0

这是基于估计是错误的。它可能假定嵌套循环的内部执行次数将比实际发生的小得多。实际上可能是[行目标走向流氓](http://dba.stackexchange.com/questions/18637/unexpected-scans-during-delete-operation-using-where-in/18746#18746)。 – 2013-05-09 08:32:14

我使用临时表中断执行顺序。它有帮助。

select 1 [x] into #tmp_87624435 
from [files].[Contacts_Migration_Template] c 
where not exists(select 1 
    from [files].[Additional_Contact_Migration_Template] 
    where contact = c.[migration id]); 
if exists(select 1 from #tmp_87624435) throw 51000, 'warning', 1; 

,但我仍然认为,即使这是矫枉过正这样一个简单的问题:)

试试这个:

if exists(

    select 1 from [files].[Contacts_Migration_Template] c left join 
    [files].[Additional_Contact_Migration_Template] a 
    on c.[migration id]=a.contact 
    where a.contact is null 
     ) 

print 'warning message' 
+0

在帖子中查看我的更正(我添加了原始查询) - 原来我已加入,但他们也一直工作很长 – 2013-05-09 08:37:29

+0

由于我办公室中的某些检查点,我无法看到您的图像。那么你在查询中使用了左连接吗? – AnandPhadke 2013-05-09 08:44:28

+0

是的。最初,我使用完全相同的查询,因为你写了:) – 2013-05-09 08:47:00