导致主要性能问题的SQL选择字段

| 我有一个存储过程,该过程连接到许多表中并从中选择字段。这些表之一是临时表。
SELECT
    a.Field1,
    a.Field2,
    b.Field3,
    b.Field4,
    c.Field5
FROM table1 a
    LEFT JOIN #table2 b ON a.Field1 = b.Field1
    INNER JOIN table3 c ON a.Field1 = c.Field1
上面的过程需要10分钟以上的时间,但是,如果我将选择中的两个
b
字段注释掉,而将连接保留在原位,则只需几秒钟即可运行。 我已将其退出程序以简化操作并保持相同的行为。执行计划也几乎相同。 任何帮助表示赞赏。     
已邀请:
        临时表中有几行,并且临时表中的“ Field2 \”是主键吗? 如果您没有从左联接的右表中选择任何行,并且联接是主键(或者可能是唯一键),并且您没有从右表中引用任何列,则SQL Server可以避免必须完全访问临时表(因为连接行的存在或不影响最终结果): 例。表格设定:
create table T1 (
    ID int not null primary key,
    Col1 varchar(10) not null
)
go
insert into T1 (ID,Col1)
select 1,\'a\' union all
select 2,\'b\' union all
select 3,\'c\'
go
create table #t2 (
    ID int not null primary key,
    Col2 varchar(10) not null
)
go
insert into #t2 (ID,Col2)
select 1,\'d\' union all
select 2,\'e\' union all
select 4,\'f\'
go
create table #t3 (
    ID int not null,
    Col3 varchar(10) not null
)
go
insert into #t3 (ID,Col3)
select 1,\'d\' union all
select 2,\'e\' union all
select 1,\'f\'
和查询:
select T1.ID,T1.Col1 from T1 left join #t2 t2 on T1.ID = t2.ID
select T1.ID,T1.Col1,t2.Col2 from T1 left join #t2 t2 on T1.ID = t2.ID
select T1.ID,T1.Col1 from T1 left join #t3 t3 on T1.ID = t3.ID
select T1.ID,T1.Col1,t3.Col2 from T1 left join #t2 t3 on T1.ID = t3.ID
在除第一个查询之外的所有查询中,联接均按预期进行。但是,由于ѭ4of中是否存在行不会影响第一个查询的最终结果,因此避免了完全执行联接。 但是,如果不是那样的话(我希望它在查询计划中有明显的不同)
        您是否尝试过反转连接? (尽管您在示例查询中缺少表c的连接条件)
SELECT
    a.Field1,
    a.Field2,
    b.Field3,
    b.Field4,
    c.Field5
FROM table1 a
    INNER JOIN table3 c
    LEFT JOIN #table2 b ON a.Field1 = b.Field1
    
        我会尝试将包含列的索引添加到included6ѭ,看看是否有帮助:
CREATE NONCLUSTERED INDEX IX_table2
    ON #table2 (Field1)
    INCLUDE (Field3, Field4);
    
        如何分两部分运行查询。使第一部分尽可能严格,然后仅对过滤集合进行外部联接。
SELECT    a.Field1,   
          a.Field2,    
          b.Field3,       
          c.Field5
INTO #t
FROM table1 a   
    INNER JOIN table3 c ON a.Field1 = c.Field1

SELECT t.Field1,
       t.field2,
       b.field3,
       b.field4,
       t.field5
FROM #t t
     LEFT OUTER JOIN #table2 b ON t.Field1 = b.Field1            
    
        
select * into #temp from table1
select * into #temp1 from table2
select * into #temp2 from table3


SELECT
    a.Field1,
    a.Field2,
    b.Field3,
    b.Field4,
    c.Field5
FROM #temp a
    LEFT JOIN #temp1 b ON a.Field1 = b.Field1
    INNER JOIN #temp2 c ON a.Field1 = c.Field1



if(Object_Id(\'TempDB..#temp\') Is Not Null)
Begin
    Drop table #temp
End
if(Object_Id(\'TempDB..#temp1\') Is Not Null)
Begin
    Drop table #temp1
End
if(Object_Id(\'TempDB..#temp2\') Is Not Null)
Begin
    Drop table #temp2
End
    

要回复问题请先登录注册