3

使用 SSMS,我如何确定哪个查询更有效?我更喜欢 A,但我被告知子查询对传输中的每一行执行一次,因此首选 B。

一个

Update t set t.transmission_status_id = 
(select transmission_status_id from transmission_status where code = 'TRANSLATED')
from transmission t
where t.transmission_status_id = 
(select transmission_status_id from transmission_status where code = 'RECEIVED')

declare @transmission_status_TRANSLATED INT = (select transmission_status_id from transmission_status where code = 'TRANSLATED')
declare @transmision_status_RECEIVED INT = (select transmission_status_id from transmission_status where code = 'RECEIVED')

Update t set t.transmission_status_id = @transmission_status_TRANSLATED
from transmission t 
where t.transmission_status_id = @transmision_status_RECEIVED

编辑:这是使用 SET STATISTICS ON 的统计信息:

一个。

Table 'transmission_status'. Scan count 1, logical reads 2, physical reads 0, 
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'transmission_status'. Scan count 1, logical reads 2, physical reads 0, 
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'transmission'. Scan count 1, logical reads 778, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'transmission'. Scan count 1, logical reads 778, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'transmission_status'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

因此,据我所知,效率没有区别。

编辑2:所以我现在明白了:由于子查询不是correlated子查询,它只执行一次。https://en.wikipedia.org/wiki/Correlated_subquery(感谢@destination_data 提供链接。)

4

2 回答 2

2

这将需要检查实际的执行计划,但我怀疑这些将是相同的。这些子查询应该只执行一次,因为它们是不相关的,而且引擎很擅长看到这些东西。

如果您真的想了解详细信息,请查看 Grant Fritchey 提供的这本免费电子书。https://www.red-gate.com/library/sql-server-execution-plans-2nd-edition

于 2016-04-15T16:45:11.660 回答
0

一种与 SSMS 中的查询进行比较的方法:

在 SSMS 中,将两个查询都包含在一个选项卡上。选择查询菜单,然后选择“包括客户统计信息”

注释掉其中一个查询,然后运行另一个。选择“客户统计”选项卡并查看统计信息。

现在注释掉另一个查询,取消注释第一个,然后再次运行。两种统计信息都将显示在“客户统计信息”选项卡中,您可以轻松查看哪个更有效。

于 2016-04-15T16:55:50.483 回答