简体   繁体   English

有关改善SQL查询计数性能的建议?

[英]Suggestions for improving count performance on a SQL query?

I've got a query that is taking a very long time to run due to a select similar to: 由于选择类似,我有一个查询要花很长时间才能运行:

SELECT 
Count( Distinct t1.v1),
Count (Distinct 
Case t2.v1 When 'blah' then t1.v1
Else null
End ),
....
FROM t1
LEFT JOIN t2 ON t1.v3 = t2.v3
WHERE t1.myDate BETWEEN @start and @end
AND t2.v5 = @id

Can anyone suggest any good methods for improving this performance? 谁能提出任何改进此性能的好方法?

As there are No Where clause predicates (no filters) on this query it will involve a complete table scan or index scan no matter what you do (unless the inner join restricts the resultset...). 由于此查询上没有where子句谓词(没有过滤器),因此无论您做什么都将涉及完整的表扫描或索引扫描(除非内部联接限制了结果集...)。

So the only improvement that you can get is possibly to affect what type of join is being done. 因此,您可以获得的唯一改进可能是影响正在执行的联接类型。 To improve the performance of the join, make sure there is an index on the t1.v3 and t2.v3 columns.... 为了提高联接的性能,请确保在t1.v3和t2.v3列上有一个索引。

Difficult to say without the big picture, what you're trying to achieve etc. 没有全局,很难说出您要达到的目标等。

But the immediate thing to check based on that is indexes - do you have suitable indexes (eg on t1.v3 / t2.v3)? 但是要立即检查的是索引-您是否有合适的索引(例如,在t1.v3 / t2.v3上)? If you do have appropriate indexes, are they indexes fragmented/statistics out of date? 如果您有适当的索引,它们的索引是否碎片化/统计信息过时?

What does the execution plan say? 执行计划怎么说?

Your LEFT JOIN on t2 with a filter on t2.v5 = @id changes this to an inner join. 您在t2上的LEFT JOIN以及在t2.v5 = @id上的过滤器将其更改为内部t2.v5 = @id You'll need ...LEFT JOIN t2 ON t1.v3 = t2.v3 AND t2.v5 = @id... 您需要...LEFT JOIN t2 ON t1.v3 = t2.v3 AND t2.v5 = @id...

Next, what indexes do you have? 接下来,您有哪些索引? Based on what I see 根据我所看到的

  • t1: (mydate, v3) INCLUDE (v1) t1 :( mydate,v3)包括(v1)
  • t2: (v3, v5) INCLUDE (v1) t2:(v3,v5)包含(v1)

You could try reversing the key cols too 您也可以尝试反转关键列

Finally, ensure all data types are correct and match (even in the 2nd count). 最后,确保所有数据类型正确且匹配(即使是第二个计数)。 Implicit conversions kill performance. 隐式转换会降低性能。

You are probably getting 1 scan on t1 and 1 seek on t2, if you are getting anything else, either the indexes are not appropriately in place, or you didn't give us enough information. 您可能在t1上进行了1次扫描,在t2上进行了1次寻道,如果您还有其他任何事情,则可能是索引位置不正确,或者您没有给我们足够的信息。

If you are getting 1 scan on t1 and 1 seek on t2, and you think this query is close to the appropriate solution (eg you cannot get the information you want from a faster query that looks nothing like this one), you may have the optimal plan. 如果您在t1上获得1次扫描,而在t2上获得1次寻道,并且您认为此查询接近适当的解决方案(例如,您无法从看起来像这样的更快查询中获得所需的信息),则可能最佳计划。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM