SQL请求执行需要很多时间
我有一个SQL查询,有时需要15秒,有时需要1分钟。 请告诉我怎么做SQL请求执行需要很多时间,sql,sql-server,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(da
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)
这是您的查询,大大简化了:
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是不必要的
然后开始添加索引。我建议:
tblEmailHistorytargetid,状态,已打开,已删除,拒绝原因,sdate
UsersSmsHistorystudentID,smsSendFullDate
我猜大多数学生都有姓名和电话号码,所以这些列上的索引不会有帮助。您的查询看起来没有多余的部分。花费大量时间的原因是,您要连接三次表,其中可能包含大量数据。因此,与其改进查询,不如尝试通过在dbo.tblEmailHistory.studentID、dbo.Students.ID等列上为表添加索引来改进表的性能是否已检查执行计划?@EdwardGizbreht。你添加索引了吗?很有效!谢谢出于好奇,将convertdate、ush.smsSendFullDate=convertdate、GETDATE子句替换为以下ush.smsSendFullDate>=convertdate、GETDATE和ush.smsSendFullDate@EvaldasBuinauskas不是更好吗。SQL Server将使用索引将日期时间转换为日期。