优化下面的sql语句,达到最优:DECLARE @dtNow VARCHAR(100) = CONVERT(VARCHAR(100),GETDATE(),23); SELECT TOP 1 k.Name kehuName ,ISNULL(MaskingApply.quanxianSum,0) quanxianSum FROM xykehu k WITH(NOLOCK) LEFT JOIN ( SELECT cs.quanxianSum,cs.AddTime FROM ClearShowApply cs WITH(NOLOCK) WHERE ISNULL(cs.IsDel,0)=0 AND cs.State='审批通过' AND cs.PowerEndTime > @dtNow AND cs.XyKehuId = @kehuId AND cs.UsersId= @userId UNION SELECT cs.quanxianSum,cs.AddTime FROM ClearShowApply cs WITH(NOLOCK) WHERE ISNULL(cs.IsDel,0)=0 AND cs.State='审批通过' AND cs.PowerEndTime > @dtNow AND cs.XyKehuId = @kehuId AND cs.CardId= @cardId ) MaskingApply ON 1 = 1 WHERE k.Id = @kehuId AND ISNULL(k.IsDel,0)=0 ORDER BY MaskingApply.AddTime DESC;
时间: 2023-11-22 12:53:01 浏览: 66
可以优化的地方如下:
1. 将GETDATE()函数调用提前到变量声明中,这样避免多次调用函数,提高效率。
2. 将SELECT TOP 1改为SELECT TOP(1),这样可以提高SQL Server执行效率。
3. 将UNION改为UNION ALL,因为前一个查询结果集和后一个查询结果集不可能存在重复记录,所以使用UNION ALL可以提高效率。
4. 将LEFT JOIN改为INNER JOIN,因为WHERE子句中已经限定了ClearShowApply表中的条件,所以不需要使用LEFT JOIN。
优化后的SQL语句如下:
```
DECLARE @dtNow VARCHAR(100) = CONVERT(VARCHAR(100), GETDATE(), 23);
SELECT TOP (1)
k.Name AS kehuName,
ISNULL(MaskingApply.quanxianSum, 0) AS quanxianSum
FROM
xykehu AS k WITH(NOLOCK)
INNER JOIN (
SELECT
cs.quanxianSum,
cs.AddTime
FROM
ClearShowApply AS cs WITH(NOLOCK)
WHERE
ISNULL(cs.IsDel, 0) = 0
AND cs.State = '审批通过'
AND cs.PowerEndTime > @dtNow
AND cs.XyKehuId = @kehuId
AND cs.UsersId = @userId
UNION ALL
SELECT
cs.quanxianSum,
cs.AddTime
FROM
ClearShowApply AS cs WITH(NOLOCK)
WHERE
ISNULL(cs.IsDel, 0) = 0
AND cs.State = '审批通过'
AND cs.PowerEndTime > @dtNow
AND cs.XyKehuId = @kehuId
AND cs.CardId = @cardId
) AS MaskingApply ON 1 = 1
WHERE
k.Id = @kehuId
AND ISNULL(k.IsDel, 0) = 0
ORDER BY
MaskingApply.AddTime DESC;
```
阅读全文