SQL请求执行需要花费很多时间

时间:2017-06-25 12:57:03

标签: sql sql-server

我有一个SQL查询,有时需要15秒,有时需要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 (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 个答案:

答案 0 :(得分: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)

我猜大多数学生都有姓名和电话号码,因此这些栏目的索引无济于事。

答案 1 :(得分:0)

您的查询看起来没问题,没有多余的部分。它需要花费大量时间的原因是因为你连接表三次并且可能有很多数据。因此,不要改进查询,而是尝试通过在indexdbo.tblEmailHistory.studentID等列上添加dbo.Students.ID来提高表格的效果