我们有一个查询,在缓存之前为我们网站上的每个用户运行。对于newrelic,查询占所有问题的大约16%。
这不是一个非常好的查询,我们应该更改表格设计,但我们需要快速修复,以便我们有时间重写此功能。
查询有时需要3秒才能运行。
这是查询。
SELECT
q.QuickLinkID
, q.QuickLinkUID
, q.SchoolID
, q.Url
, q.Name
, q.Target
, q.OnlyTeachers
, q.UserNumber
FROM
Quicklinks AS q WITH (NOLOCK)
LEFT JOIN
schoolParticipants AS sp WITH (NOLOCK) ON q.schoolID = sp.schoolID
WHERE
(sp.userID = ? OR q.UserNumber = ?)
AND (q.schoolID = ? OR q.SchoolID NOT IN (SELECT qe.SchoolID
FROM Quicklinkexclude AS qe WITH (NOLOCK)
WHERE qe.userID = ?))
AND ((sp.isTeacher > ? AND q.OnlyTeachers = ?) OR q.OnlyTeachers = ?)
ORDER BY
q.Name
答案 0 :(得分:0)
将子查询更改为连接并在ID列上应用索引:
SELECT q.QuickLinkID
, q.QuickLinkUID
, q.SchoolID
, q.Url
, q.Name
, q.Target
, q.OnlyTeachers
, q.UserNumber
FROM Quicklinks AS q WITH (NOLOCK)
LEFT JOIN schoolParticipants AS sp WITH (NOLOCK) ON q.schoolID = sp.schoolID
LEFT OUTER JOIN QuickLinkexclude AS qe ON q.SchoolID = qe.SchoolID
WHERE (sp.userID = ? OR q.UserNumber = ?)
AND qe.SchoolID IS NULL
AND qe.userID = ?
AND ((sp.isTeacher > ? AND q.OnlyTeachers = ?) OR q.OnlyTeachers = ?)
子查询可能会导致表扫描。使用连接,如果您使用正确的索引,它可以是搜索,在大多数情况下速度要快得多。
未经测试,但这应该有效。