SQL Server:联合后的内部联接导致哈希匹配速度慢(聚合)
下面是一个使整个存储过程变慢的CTE:SQL Server:联合后的内部联接导致哈希匹配速度慢(聚合),sql,tsql,sql-server-2008,union,Sql,Tsql,Sql Server 2008,Union,下面是一个使整个存储过程变慢的CTE: select * from #finalResults where intervalEnd is not null union select two.startTime, two.endTime, two.intervalEnd, one.barcodeID, one.id, one.pairId, one.bookingTypeID, one.cardID,
select *
from #finalResults
where intervalEnd is not null
union
select
two.startTime,
two.endTime,
two.intervalEnd,
one.barcodeID,
one.id,
one.pairId,
one.bookingTypeID,
one.cardID,
one.factor,
two.openIntervals,
two.factorSumConcurrentJobs
from #finalResults as one
inner join #finalResults as two
on two.cardID = one.cardID
and two.startTime > one.startTime
and two.startTime < one.intervalEnd
我是否也需要在此基础上构建一个单独的统计数据?我曾经遇到过这样的情况:UNION的查询速度比UNION的查询速度慢得多,而UNION的所有查询都有一个不同的结果。因此,虽然我无法解释错误的查询计划统计信息和索引是否正常,但我建议您尝试以下方法:
select distinct * from (
select *
from #finalResults
where intervalEnd is not null
union all
select
two.startTime,
two.endTime,
two.intervalEnd,
one.barcodeID,
one.id,
one.pairId,
one.bookingTypeID,
one.cardID,
one.factor,
two.openIntervals,
two.factorSumConcurrentJobs
from #finalResults as one
inner join #finalResults as two
on two.cardID = one.cardID
and two.startTime > one.startTime
and two.startTime < one.intervalEnd
)
如果您为cardID列创建统计信息,它可能会有所改进。我已经这样做了:它提供了与使用optionorder组从原始CTE中选择相同的执行计划,即它花费的时间与以前相同,它只是将其用于排序而不是哈希。是的,查看该查询计划,散列匹配只有一个输入-因此是联合删除重复项导致了问题,我看不到任何关于连接的提示。也许使用一个UNION ALL,您可以确保不使用Èexcept添加重复记录,因为这样可以避免对第一部分的580K行进行排序?它不是散列联接,而是散列匹配。这是联合运算符注释的重复删除,它只有一个输入
select distinct * from (
select *
from #finalResults
where intervalEnd is not null
union all
select
two.startTime,
two.endTime,
two.intervalEnd,
one.barcodeID,
one.id,
one.pairId,
one.bookingTypeID,
one.cardID,
one.factor,
two.openIntervals,
two.factorSumConcurrentJobs
from #finalResults as one
inner join #finalResults as two
on two.cardID = one.cardID
and two.startTime > one.startTime
and two.startTime < one.intervalEnd
)