使用嵌套选择减慢TSQL查询

时间:2014-01-07 09:40:21

标签: sql tsql sql-server-2012

我编写了一个查询,但在我们的实时环境中似乎运行得相当慢。 该查询包含嵌套的select语句,我相信这会减慢执行速度。

有没有人知道如何重新编写查询以提高执行速度。

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME

SET @StartDate = '20140101'
SET @EndDate = '20140101'

SELECT a.applicationid,
       a.ourreference,
       (SELECT MAX(e.CreateDateTime) FROM tblEmail AS e WHERE( e.ApplicationID = a.ApplicationID) AND (ISNULL(e.StandardEmailID,0) <> 3)) AS 'LastEmail',
       (SELECT MAX(l.CreateDateTime) FROM tblLetter AS l WHERE l.ApplicationID = a.ApplicationID AND l.ExternalDocumentTypeID IS NULL) AS 'LastInternalLetter',
       (SELECT MAX(l.CreateDateTime) FROM tblLetter AS l WHERE l.ApplicationID = a.ApplicationID AND l.ExternalDocumentTypeID IS NOT NULL) AS 'LastExternalLetter'
INTO #Temp
FROM tblapplication AS a
WHERE (a.LogDate BETWEEN @StartDate AND @EndDate + '23:59:59')
AND (a.BusinessSourceID NOT IN (11, 16))
AND (a.ApplicationStatusID = 100)

SELECT *
FROM #Temp AS tem
WHERE ((LastEmail < LastExternalLetter) AND (LastInternalLetter < LastExternalLetter))

为每个人欢呼

编辑 - 抱歉,我应该说出查询的用途。我想看看我们的客户是否给我们发了一封信,但我们没有用信件/电子邮件回复他们

1 个答案:

答案 0 :(得分:1)

select *
from
(
    Select a.applicationId, a.ourreference,
           max(e.CreateDateTime) LastEmail,
           max(li.CreateDateTime) LastInternalLetter,
           max(le.CreateDateTime) LastExternalLetter
    from tblApplication a
    left outer join tblEmail e on e.ApplicationID = a.ApplicationID 
    left outer join tblLetter li on li.ApplicationId = a.ApplicationId
    left outer join tblLetter le on le.ApplicationId = a.ApplicationId
    WHERE (a.LogDate BETWEEN @StartDate AND @EndDate + '23:59:59')
    AND (a.BusinessSourceID NOT IN (11, 16))
    AND (a.ApplicationStatusID = 100)
    and (e.StandardEmailID <> 3 or e.StandardEmailId is null)
    group by a.ApplicationId, a.OurReference
)x
WHERE ((LastEmail < LastExternalLetter) AND (LastInternalLetter < LastExternalLetter))

这摆脱了临时表。请记住,使用SQL,只要有表,就可以替换查询(无论如何都选择)。这应该会提高效率,但是你想查看查询计划,看看是什么阻碍了它。

干杯 -