简体   繁体   English

如何优化这个select语句?

[英]How to optimise this select statement?

The below statement is taking almost 2 minutes to execute, when a slightly different select statement using the same tables and views with the same results is taking half that:下面的语句需要将近 2 分钟的时间来执行,当使用相同的表和视图并具有相同结果的略有不同的 select 语句执行一半时:

SELECT
@NEW_CAREER_NUMBER = MAX(a.[career number])
FROM selecthr20.employee.[career history] a 
    INNER JOIN selecthr20.Employee.[Current Appointments As At Evaluation Date] b
        ON a.[appointment number] = b.[appointment number]  
    INNER JOIN Employee.[BSK Changes in Selected Period] c
        ON a.[career number] = c.[primary key number]
    INNER JOIN selecthr20.employee.[career history extra detail] d
        ON a.[career number] = d.[career number]
            AND c.[primary key number] = d.[career number]
where c.[primary key name] = 'Career Number'
and c.[audit date] < (Select max([audit date]) from Employee.[BSK Changes in Selected Period] where [primary key number] = @LATEST_CAREER_NUMBER)
and b.[person number] = @PERSON_ID

'[BSK changes in Selected Period] c' is a view, the rest are tables. '[BSK在Selected Period的变化] c'是一个视图,其余都是表。

You had a redundant condition on the d join你在 d join 上有一个多余的条件
Give this a try试试这个

SELECT
@NEW_CAREER_NUMBER = MAX(a.[career number])
FROM selecthr20.employee.[career history] a 
JOIN selecthr20.Employee.[Current Appointments As At Evaluation Date] b
      ON b.[appointment number] = a.[appointment number] 
     and b.[person number]      = @PERSON_ID  
JOIN selecthr20.employee.[career history extra detail] d
      ON d.[career number] = a.[career number] 
JOIN Employee.[BSK Changes in Selected Period] c
      ON c.[primary key number] = a.[career number] 
     and c.[primary key name]   = 'Career Number'
     and c.[audit date] < ( Select max([audit date])   
                              from Employee.[BSK Changes in Selected Period]
                             where [primary key number] = @LATEST_CAREER_NUMBER );

Naturally put an index on the join conditions自然地在连接条件上放一个索引

And if you have a loop on the c join then use a variable for audit date如果您在 c 连接上有一个循环,则使用一个变量作为审计日期
I would just do this - there is very little down side我会这样做 - 几乎没有不利的一面

declare @auditdate DateTime = ( Select max([audit date]) 
                                  from Employee.[BSK Changes in Selected Period] 
                                 where [primary key number] = @LATEST_CAREER_NUMBER );

... 

and c.[audit date] < @auditdate 

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

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