查询调整和重写 - SQL 服务器

Query Tuning and rewrite - SQL Server

您能否帮助优化以下查询以使其性能更好?我可以降低成本吗?

SELECT this_.id               AS id1_20_0_, 
       this_.version          AS version2_20_0_, 
       this_.domain           AS domain4_20_0_, 
       this_.createdate       AS createda5_20_0_, 
       this_.lastmodifydate   AS lastmodi6_20_0_, 
       this_.ownerid          AS ownerid7_20_0_, 
       this_.timeperiod       AS timeperi8_20_0_, 
       this_.type             AS type9_20_0_, 
       this_.capturesource    AS capture10_20_0_, 
       this_.value            AS value11_20_0_, 
       this_.siteid           AS siteid12_20_0_, 
       this_.lastmodifyuserid AS lastmod13_20_0_, 
       this_.classid          AS classId3_20_0_ 
FROM   dbo.pcwdepconstraints this_ 
WHERE  this_.classid = 65 
       AND this_.ownerid = 200000000001 
       AND ( this_.capturesource IS NULL 
              OR this_.capturesource IN ( 1073741826, 1073741827, 0, 1, 2 ) ) 

我已经通过下面的列重新创建了 ix2_pcwdepcons,但是执行计划及其成本仍然没有变化。

( this_.id , 
       this_.version   , 
       this_.domain ,
       this_.createdate  ,
       this_.lastmodifydate,

       this_.timeperiod  ,
       this_.type  , 
        this_.value   ,       
       this_.siteid       
       this_.lastmodifyuserid )

执行计划显示您有一个查找(查找基本信息),但随后还有一个 "key lookup",这是一个相当昂贵的操作,您应该尽可能避免。

查看查询,我看到您在 WHERE 子句中使用了 classidowneridcapturesource - 因此这些需要在索引中.如果可以,您还可以将查询的 SELECT 子句中的所有其他列 "include" 放入该索引,以避免 "key lookup".

所以我想试试这样的索引:

CREATE NONCLUSTERED INDEX IX_Test
ON dbo.pcwdepconstraints_bkp (classid, ownerid, capturesource)
INCLUDE (id, version, domain, createdate, lastmodifydate, lastmodifyuserid,
         timeperiod, type, value, siteid)

仅当这不是来自 table 的整个列列表时,包含那么多列才有意义。这些列将占用 space,因此您需要权衡提高查询性能与需要更多磁盘 space。但是,如果您的 table 列更多并且您的查询选择了 "only" 那 13 个(因为它确实需要那些),那么 INCLUDE 确实有助于加快速度。