2017-06-25 8 views
0

私は時には15秒、場合によっては1分かかるSQLクエリを持っています。 質問を軽くする方法を教えてください。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

あなたの質問は冗長な部分がないと大丈夫です。時間がかかる理由は、テーブルを3回結合しているために、その中に多くのデータがある可能性があるからです。したがって、クエリを改善する代わりに、dbo.tblEmailHistory.studentIDdbo.Students.IDなどのindexを追加してテーブルのパフォーマンスを向上させてください。

関連する問題