优化查询作为其慢人

时间:2016-12-27 15:03:19

标签: sql sql-server

select distinct m1.jobreference,m1.assid,m2.assid 
From dbo.mess m1
inner join dbo.mess m2 
    on m1.JobReference=m2.jobreference and m1.assid!=m2.assid
where 
m1.jobreference not in ( 
select Jobreference from dbo.mess where routingkey='j.asschanged')

4958行受影响

表&#39>表'混乱'扫描计数20,逻辑读取359816,物理读取525,预读读取4626,lob逻辑读取0,lob物理读取0,lob预读读取0。 表'工作文件'。扫描计数0,逻辑读取0,物理读取0,预读取读取0,lob逻辑读取0,lob物理读取0,lob预读读取0。 表'工作台'。扫描计数0,逻辑读取0,物理读取0,预读读取0,lob逻辑读取0,lob物理读取0,lob预读读取0. 强文本

2 个答案:

答案 0 :(得分:1)

Sub-Query不需要。试试这种方式

SELECT m1.jobreference,
       m1.assid,
       m2.assid
FROM   dbo.mess m1
       INNER JOIN PRD_Phoenix.dbo.mess m2
               ON m1.JobReference = m2.jobreference
                  AND m1.assid != m2.assid
Group By  m1.jobreference,m1.assid,m2.assid
Having count(case when m1.routingkey = 'j.asschanged' then 1 end) = 0

如果您确实需要删除重复项,请使用Distinct。如果您的查询不会产生重复,或者您不担心重复,请从查询中删除DISTINCT关键字

答案 1 :(得分:1)

我首先将查询编写为:

select distinct jobreference, assid, assid2
from (select m1.jobreference, m1.assid, m2.assid as assid2,
             sum(case when m2.routingkey = 'j.asschanged' then 1 else 0 end) over (partition by m2.jobreference) as cnt
      from dbo.mess m1 inner join
           PRD_Phoenix.dbo.mess m2 
           on m1.JobReference = m2.jobreference and m1.assid <> m2.assid
     ) mm
where cnt = 0;

然后,您要考虑明显的索引是m2(jobreference, assid)m1(jobference, assid)

我担心select distinct和高基数连接的可能性。如果没有关于数据结构的更多信息,很难提出进一步的建议。