提高查询的性能

时间:2014-03-13 06:49:46

标签: sql sql-server

我的查询花了很长时间。

select distinct JobName,
       ValidationType,
       AppName,
       Result,
       ResultType,
       ErrorWarningDetails,
       CvtStartDateTime 
  from contentvalidationjobdetails with (nolock)
 where appname=@AppName 
       and result=@Result 
       and (cast(cvtstartdatetime as date) > @Date )
       and concat(Jobname,validationtype) not in (
                  select concat(jobname,validationtype) 
                    from Contentvalidationjobdetails with (nolock) 
                   where appname = @AppName 
                         and CVTStartDateTime = (
                          select top 1 teststartdatetime 
                            from contentvalidation 
                           where appname=@AppName 
                                 and Teststartdatetime<@Date
                        order by teststartdatetime desc
                         )
           )

我知道concat(jobname,validationtype)需要时间。如何处理这个。

1 个答案:

答案 0 :(得分:1)

将查询放在FROm部分中,只执行一次(不适用于WHERE中的每一行)。添加外部联接并仅保留没有联接的记录。

select distinct JobName,
       ValidationType,
       AppName,
       Result,
       ResultType,
       ErrorWarningDetails,
       CvtStartDateTime 
  from contentvalidationjobdetails with (nolock)
       LEFT OUTER JOIN (
                  select concat(jobname,validationtype) cnt
                    from Contentvalidationjobdetails with (nolock) 
                   where appname = @AppName 
                         and CVTStartDateTime = (
                          select top 1 teststartdatetime 
                            from contentvalidation 
                           where appname=@AppName 
                                 and Teststartdatetime<@Date
                        order by teststartdatetime desc) sub ON concat(Jobname,validationtype)=sub.cnt

 where appname=@AppName 
       and result=@Result 
       and (cast(cvtstartdatetime as date) > @Date ))
  HAVING sub.cnt is null 
相关问题