我需要获得用户数量。当我在OR
子句中添加WHERE
条件时,执行查询需要更多时间。如何优化此SQL查询以最小化执行时间?
SELECT SM.ModelId,
SM.NameID,
U.UserCount INTO #SM
FROM Mapper AS SM (NOLOCK) CROSS APPLY (
SELECT COUNT(DISTINCT U.UserNumber) AS UserCount
FROM Team T (NOLOCK)
JOIN Equ E (NOLOCK) ON T.Equid = E.Equid
JOIN EquReq ER (NOLOCK) ON E.EquReqid = ER.EquReqid
LEFT JOIN Information I (NOLOCK) ON T.Equid = I.Equid
JOIN USER U (NOLOCK) ON ER.Key = U.Key
WHERE (T.NameID = SM.NameID
OR I.NameID = SM.NameID)
答案 0 :(得分:0)
您可以尝试运行以下内容 -
SELECT SM.ModelId, SM.NameID, U.UserCount
INTO #SM
FROM Mapper AS SM (NOLOCK)
CROSS APPLY (SELECT COUNT(DISTINCT U.UserNumber) AS UserCount
FROM Team T (NOLOCK)
JOIN Equ E (NOLOCK)
ON T.Equid = E.Equid
JOIN EquReq ER (NOLOCK)
ON E.EquReqid = ER.EquReqid
LEFT JOIN Information I (NOLOCK)
ON T.Equid = I.Equid
JOIN User U (NOLOCK)
ON ER.Key = U.Key
WHERE T.NameID = SM.NameID
UNION
SELECT COUNT(DISTINCT U.UserNumber) AS UserCount
FROM Team T (NOLOCK)
JOIN Equ E (NOLOCK)
ON T.Equid = E.Equid
JOIN EquReq ER (NOLOCK)
ON E.EquReqid = ER.EquReqid
LEFT JOIN Information I (NOLOCK)
ON T.Equid = I.Equid
JOIN User U (NOLOCK)
ON ER.Key = U.Key
WHERE I.NameID = SM.NameID)
如果这没有帮助,请确保在T.NameID和amp;上都有足够的覆盖索引。 I.NameID以满足查询。
如果您仍有问题,请告诉我您在下表中的索引 -
T队 信息我