如果我检查[deliverybody]字段是否包含'x',则第一个/未缓存的查询需要很长时间,以消除带有'x'的行。如果我不检查'x',[deliverytime]会被索引并在一秒钟内完成查询。
使用 AND [deliverybody]<> 'x'部分查询执行时间为10+秒,没有; 1秒。看起来索引字段[deliverytime]似乎无济于事。
查询仅返回1600行。扫描额外的1600个字段需要10秒以上。查询出了什么问题?
更新:从NTEXT升级到NVARCHAR(MAX)。内部查询的执行计划:
此查询需要10秒以上:
SELECT MAX([deliveryid]) AS deliveryid, COUNT(*) AS cnt
FROM [_hMaiServer].[dbo].[hm_deliverylog]
WHERE [deliverytime] > DATEADD(HOUR, -24, GETDATE())
AND [deliverybody] <> 'x'
GROUP BY deliverysubject
查询在第二天完成:
SELECT MAX([deliveryid]) AS deliveryid, COUNT(*) AS cnt
FROM [_hMaiServer].[dbo].[hm_deliverylog]
WHERE [deliverytime] > DATEADD(HOUR, -2400, GETDATE())
--AND [deliverybody] <> 'x'
GROUP BY deliverysubject
包含索引的表结构:http://pastebin.com/W0PsDnqS
我的结论:
检查5000行需要10秒以上。较小的 {HOUR} 值会使执行时间更快。如果可以,这里没问题,但对我来说似乎很慢。
SELECT COUNT(*) FROM [hm_deliverylog]
WHERE [deliverybody] <> 'x'
AND [deliverytime] > DATEADD(HOUR, -__{HOUR}__ , GETDATE())
答案 0 :(得分:1)
您尚未提供所请求的SET STATISTICS IO ON;
结果。
然而,一种可能的改进可能不是使用
WHERE [deliverybody] <> 'x'
使用
WHERE NOT (LEN([deliverybody]) = 1 AND LEFT([deliverybody],1) = 'X')
以下有益的例子。
CREATE TABLE T1
(
Id INT,
[deliverybody] VARCHAR(MAX)
)
INSERT INTO T1
VALUES (1, Replicate(Cast('A' AS VARCHAR(MAX)), 2000000000)),
(2,'X')
SET STATISTICS IO ON;
SELECT id
FROM T1
WHERE NOT ( Len([deliverybody]) = 1
AND LEFT([deliverybody], 1) = 'X' )
SELECT id
FROM T1
WHERE [deliverybody] <> 'X'
DROP TABLE T1
两者的IO结果均低于
Table 'T1'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0
, lob logical reads 6, lob physical reads 0, lob read-ahead reads 0.
Table 'T1'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0
lob logical reads 2209665, lob physical reads 0, lob read-ahead reads 642255.
第一个读取数量明显减少,因为它避免拖出整个2GB值,以发现它不是X