2017-06-25 71 views
0

我有一個SQL查詢需要15秒,有時需要1分鐘。 請告訴我,我可以做我的查詢更輕。執行SQL請求花費很多時間

SELECT TOP 100 
u.firstName, 
u.id as userID, 
ueh.targetID, 
ueh.opened, 
ueh.emailID, 
u.phone, 
u.gender 
FROM dbo.Students u 
INNER JOIN dbo.tblEmailHistory ueh 
ON ueh.studentID = u.ID 
WHERE (CONVERT(date,DATEADD(day,6,ueh.sDate))=CONVERT(date,getdate())) 
AND IsNull(u.firstName, '') != '' 
AND IsNull(u.email, '')  != '' 
AND IsNull(u.phone, '')  != '' 
AND ueh.status = 'sent' 
AND ueh.reject_reason = 'null' 
AND ueh.targetID = 28 
AND ueh.opened = 0 
AND u.deleted = 0 
AND NOT EXISTS (SELECT ush.smsSendFullDate, ush.studentID FROM dbo.UsersSmsHistory ush WHERE u.id = ush.studentID AND DATEDIFF(DAY,ush.smsSendFullDate,GETDATE()) = 0) 
+2

您是否已檢查執行計劃? –

回答

1

這是您的查詢大大簡化:

SELECT TOP 100 u.firstName, u.id as userID, 
     ueh.targetID, ueh.opened, ueh.emailID, 
     u.phone, u.gender 
FROM dbo.Students u INNER JOIN 
    dbo.tblEmailHistory ueh 
    ON ueh.studentID = u.ID 
WHERE ueh.sDate >= cast(getdate() + 6 as date) AND 
     ueh.sDate < csat(getdate() + 7 as date) AND 
     u.firstName <> '' AND 
     u.email <> '' AND 
     u.phone <> '' AND 
     ueh.status = 'sent' AND 
     ueh.reject_reason = 'null' AND -- sure you mean a string here? 
     ueh.targetID = 28 AND 
     ueh.opened = 0 AND 
     u.deleted = 0 AND 
     NOT EXISTS (SELECT ush.smsSendFullDate, ush.studentID 
        FROM dbo.UsersSmsHistory ush 
        WHERE u.id = ush.studentID AND 
         convert(date, ush.smsSendFullDate) = convert(date, GETDATE()) 
       ); 

注:比較來NULL從不幾乎所有的比較真實,所以ISNULL()/COALESCE()是不必要的。

然後開始添加索引。我建議:

  • tblEmailHistory(targetid, status, opened, deleted, rejectreason, sdate)
  • UsersSmsHistory(studentID, smsSendFullDate)

我猜大多數學生有姓名和電話號碼,所以對這些列的索引將不會幫助。

+0

沒有幫助,謝謝 –

+0

@EdwardGizbreht。 。 。你添加了索引嗎? –

+0

它工作!謝謝! –

0

您的查詢看起來沒問題,沒有多餘的零件。花費大量時間的原因是因爲您要連接三次表格,並且可能會有很多數據。因此,除了改善您的查詢外,還可以嘗試通過在dbo.tblEmailHistory.studentID,dbo.Students.ID等列上添加index來提高表的性能。

相關問題