0

如何优化此查询:

declare @MyParam nvarchar(100) = 25846987;

select top 100 * from MySelectTable
where
(MyParam = @MyParam)
OR
(@MyParam = 0 and MyParam in (SELECT MyParam FROM aMassiveSlowTable WHERE Id = 'random1'))
OR
(@MyParam = 1 and MyParam in (SELECT MyParam FROM aMassiveSlowTable WHERE Id = 'random2'))
OR
(@MyParam = 2 and MyParam in (SELECT MyParam FROM aMassiveSlowTable WHERE Id = 'random3'))

当我只使用这部分时:

declare @MyParam nvarchar(100) = 25846987;

select top 100 * from MySelectTable
where
(MyParam = @MyParam)

它会在 1 秒内返回。

使用所有参数时,大约需要 5 分钟。

我相信这是因为它正在扫描 aMassiveSlowTable,而它所要做的就是匹配 MyParam = @MyParam。

如果@MyParam 与 MyParam 匹配,如何让它跳过所有其他比较?我尝试使用 CASE 语句,但它们不适用于IN子句。我尝试重新排列括号中的 AND,甚至向aMassiveSlowTable添加额外的过滤。

如果@MyParam 与MyParam 不匹配,则查询需要更长的时间也没关系。

4

2 回答 2

0

至于您的问题“使用所有参数时”的性能方面,您可能需要查看以下知识库:

修复:在 SQL Server 2008 或 SQL Server 2008 R2 或 SQL Server 2012 中运行包含相关 AND 谓词的查询时性能不佳

http://support.microsoft.com/kb/2658214

于 2012-10-06T15:06:46.980 回答
0

这可能会解决它
在应该尽早评估的地方

(MyParam in (SELECT MyParam FROM aMassiveSlowTable WHERE Id = 'random1' and @MyParam = 0 )) 

或者

declare @MyParam nvarchar(100) = 25846987;
select * 
from MySelectTable
where MyParam = @MyParam 
union
select *  
from MySelectTable
join aMassiveSlowTable as Slow 
 and Slow.MyParam = MySelectTable.MyParam 
 and Slow.ID = 'random0'
where @MyParam = 0
union
select *  
from MySelectTable
join aMassiveSlowTable as Slow 
 and Slow.MyParam = MySelectTable.MyParam 
 and Slow.ID = 'random1'
where @MyParam = 1
union
select *  
from MySelectTable
join aMassiveSlowTable as Slow 
 and Slow.MyParam = MySelectTable.MyParam 
 and Slow.ID = 'random2'
where @MyParam = 2

或玩加入提示

declare @MyParam nvarchar(100) = 25846987;
select top 100 * 
from MySelectTable
left join aMassiveSlowTable as Slow 
  on Slow.MyParam in (1,2,3)  -- now the optimizer has something hard to evalate
 and Slow.MyParam = MySelectTable.MyParam 
 or (Slow.MyParam = 0 and Slow.ID = 'random0')
 or (Slow.MyParam = 1 and Slow.ID = 'random1')
 or (Slow.MyParam = 2 and Slow.ID = 'random2')
where MyParam = @MyParam
于 2012-10-05T21:46:09.820 回答