用sqlserver语法优化下面的代码并说明优化原因:select top 100 id from pfPhoneUpdate with(nolock) where bh in ( /*Id、shfzh*/ select cd.Id FROM dbo.CardInfo cd WITH(NOLOCK) WHERE cd.InPiciId >= @pici AND ISNULL(cd.IsDel, 0) = 0 AND NOT EXISTS ( SELECT 1 FROM XyPhone x WITH(NOLOCK) WHERE cd.Shfzh = x.Shfzh AND ISNULL(x.IsDel, 0) = 0 AND x.AddUserId = 'pfAuto' ) ) AND ISNULL(upCount,0) < 4 AND ISNULL(pfPhoneFlag,0)=0
时间: 2023-12-08 17:05:19 浏览: 114
sql语句的优化
以下是优化后的代码:
```
SELECT TOP 100 pu.id
FROM pfPhoneUpdate pu WITH(NOLOCK)
INNER JOIN dbo.CardInfo cd WITH(NOLOCK) ON pu.bh = cd.Id
LEFT JOIN XyPhone x WITH(NOLOCK) ON cd.Shfzh = x.Shfzh AND x.AddUserId = 'pfAuto'
WHERE cd.InPiciId >= @pici
AND ISNULL(cd.IsDel, 0) = 0
AND ISNULL(pu.upCount, 0) < 4
AND ISNULL(pu.pfPhoneFlag, 0) = 0
AND x.Shfzh IS NULL
AND ISNULL(x.IsDel, 0) = 0
```
优化原因:
1.使用INNER JOIN代替IN语句,这样可以避免在子查询中逐条查询,提高了查询效率。
2.使用LEFT JOIN和IS NULL来检查子查询的结果,避免了使用NOT EXISTS语句,提高了查询效率。
3.将所有的ISNULL函数调用移到WHERE子句中,而不是在子查询中使用,这样可以避免对每一条记录进行处理,提高了查询效率。
4.将WHERE子句的顺序调整为更加优化的顺序,这样可以进一步提高查询效率。
阅读全文