在 where 子句中添加 OR 条件后,SQL 视图性能会提高



我有一个这样的视图,执行大约需要 2 分钟。

select col1, col2, col3, col4, ..., 
from table1 
inner join table2 on condition1
inner join table3 on condition2
inner join table4 on condition3
....
left outer join table12 on condition11
left outer join table13 on condition12
...
where condition13 and condition14 and condition15

但是如果我在视图中添加一个OR条件,性能会急剧增加,大约需要 13 秒。在这种情况下,OR条件永远不会成立。col1table2上的主键,知道为什么会发生这种情况,并且有没有一种巧妙的方法来实现这些结果。

OR table2.col1 = 0

更改的查询:

select col1, col2, col3, col4, ..., 
from table1 
inner join table2 on condition1
inner join table3 on condition2
inner join table4 on condition3
....
left outer join table12 on condition11
left outer join table13 on condition12
...
where condition13 and condition14 and condition15 OR table2.col1 = 0

提前致谢

我设计了两个简单的POC:

  • Case A,http://sqlfiddle.com/#!18/d0c53/1,带有带过滤器的直截了当的inner join
  • Case B, http://sqlfiddle.com/#!18/d0c53/5,具有相同的inner join和相同的过滤器加上ORed条件,不会产生额外的结果

请检查两种情况的执行计划,单击链接查看执行计划

对于Case A有一个嵌套循环(具有非聚集索引搜索(,而对于Case B来说,合并连接可能耗时更少(尽管肯定需要更多的缓冲区空间(。

相同的结果集,非常不同的执行计划。

考虑到您的问题,这些案例向我们展示了什么?好吧,对不起,除了公牛什么都没有。

我试图在这里演示查询中的单个调整会产生与 SQL Server 引擎完全不同的行为。

更重要的是,这里没有显示:统计数据的准确性和新鲜度对引擎计划的影响更大——突然间,快速查询可能会因为统计数据的变化而变得迟钝,而不是数据的变化,也不是查询本身的变化。

由于您没有向我们提供实际数据和查询,因此您必须自行调查查询计划,以设计为什么这两个查询的行为如此不同。

而且,欢迎来到这个美妙的查询调优世界!希望你喜欢它。

最新更新