我有两个查询来过滤一些用户ID依赖于问题及其答案。
查询A是(原始版本):
SELECT userid
FROM mem..ProfileResult
WHERE ( ( QuestionID = 4
AND QuestionLabelID = 0
AND AnswerGroupID = 4
AND ResultValue = 1
)
OR ( QuestionID = 14
AND QuestionLabelID = 0
AND AnswerGroupID = 19
AND ResultValue = 3
)
OR ( QuestionID = 23
AND QuestionLabelID = 0
AND AnswerGroupID = 28
AND ( ResultValue & 16384 > 0 )
)
OR ( QuestionID = 17
AND QuestionLabelID = 0
AND AnswerGroupID = 22
AND ( ResultValue = 6
OR ResultValue = 19
OR ResultValue = 21
)
)
OR ( QuestionID = 50
AND QuestionLabelID = 0
AND AnswerGroupID = 51
AND ( ResultValue = 10
OR ResultValue = 41
)
)
)
GROUP BY userid
HAVING COUNT(*) = 5
我使用'set statistics time on'和'set statistic io on'来检查cpu时间和io性能。
结果是:
CPU time = 47206 ms, elapsed time = 20655 ms.
我通过使用Set Operation重写了Query A,让我把它命名为Query B:
SELECT userid
FROM ( SELECT userid
FROM mem..ProfileResult
WHERE QuestionID = 4
AND QuestionLabelID = 0
AND AnswerGroupID = 4
AND ResultValue = 1
INTERSECT
SELECT userid
FROM mem..ProfileResult
WHERE QuestionID = 14
AND QuestionLabelID = 0
AND AnswerGroupID = 19
AND ResultValue = 3
INTERSECT
SELECT userid
FROM mem..ProfileResult
WHERE QuestionID = 23
AND QuestionLabelID = 0
AND AnswerGroupID = 28
AND ( ResultValue & 16384 > 0 )
INTERSECT
SELECT userid
FROM mem..ProfileResult
WHERE QuestionID = 17
AND QuestionLabelID = 0
AND AnswerGroupID = 22
AND ( ResultValue = 6
OR ResultValue = 19
OR ResultValue = 21
)
INTERSECT
SELECT userid
FROM mem..ProfileResult
WHERE QuestionID = 50
AND QuestionLabelID = 0
AND AnswerGroupID = 51
AND ( ResultValue = 10
OR ResultValue = 41
)
) vv;
CPU时间和经过时间是:
CPU time = 8480 ms, elapsed time = 18509 ms
从最高结果可以看出,查询A的CPU时间超过经过时间的2倍
我搜索这种情况,大多数人都说CPU时间应该小于经过的时间,因为CPU时间是CPU运行这个任务多长时间。经过的时间包括I / O时间和其他类型的时间成本。但有一个特例是Server有多个Core CPU。但是,我刚刚检查了开发数据库服务器,它有一个单核CPU。如何在单核CPU环境中解释CPU时间超过查询A中的经过时间?
之后,使用set操作,性能是否真的得到改善?
我有这个问题,因为查询B的逻辑读取是280627,高于查询A的241885
Brad McGehee在他的文章'The fewer the logical reads performed by a query, the more efficient it is, and the faster it will perform, assuming all other things are held equal.'
中说然而,是否正确地说,即使查询B具有比查询A更高的逻辑读取,但CPU时间明显小于查询A,查询B应该具有更好的性能。
答案 0 :(得分:9)
如果CPU大于已用时,您确实多核或超线程CPU
CPU时间是SQL Server Engine的安装位置。它不适用于本地Management Studio安装。
对于逻辑IO与CPU,我会选择较低的CPU。如果这经常运行并且重叠,那么您将首先耗尽CPU资源。我会尝试一个WHERE EXISTS(UNION ALL)构造,并确保我有很好的索引。
在评论之后编辑
答案 1 :(得分:2)
在我的情况下 - SQL Server执行时间: CPU时间= 671 ms,经过时间= 255 ms。
CPU时间几乎是查询所用时间的三倍。因为查询 并行处理,CPU负担非常高,CPU可能成为瓶颈 对于这种情况。
SQL Server 2012带来了CPU负担问题的解决方案。它介绍了迭代器 它一次处理一批行,而不是一行一行。
对于查询优化,您可以在表上创建列存储索引 -
CREATE COLUMNSTORE INDEX idx_cs_colname ON dbo.Tablename(feild1,feild2);