哈希联接是第三种物理联接运算符,当说到哈希联接时,它是三种联接运算中性能最好的.嵌套循环联接适用于相对较小的数据集,而合并联接适用于中等规模的数据集,而哈希联接则适用于大规模联接的数据集.
哈希联接算法采用"构建"和"探测"两步来执行.在"构建"阶段,它首先从第一个输入中读取所有行(常叫做左或构建输入)在相等联接键上对这些行进行哈希,然后在内存中创建哈希表,在"探测"阶段,从第二个输入中读取所有行(常叫做右中探测输入)在相的等值联接键上对这些行进行哈希,查找可探测该哈希表中匹配的行.
下面是伪代码描述:
for each row R1 in the build table
begin
calculate hash value on R1 join key(s)
insert R1 into the appropriate hash bucket
end
for each row R2 in the probe table
begin
calculate hash value on R2 join key(s)
for each row R1 in the corresponding hash bucket
if R1 joins with R2
output (R1, R2)
end
示例:
创建表对象架构:
create table T1 (a int, b int, x char(200))
create table T2 (a int, b int, x char(200))
create table T3 (a int, b int, x char(200))
set nocount on
declare @i int
set @i = 0
while @i < 1000
begin
insert T1 values (@i * 2, @i * 5, @i)
set @i = @i + 1
end
GO
declare @i int
set @i = 0
while @i < 10000
begin
insert T2 values (@i * 3, @i * 7, @i)
set @i = @i + 1
end
GO
declare @i int
set @i = 0
while @i < 100000
begin
insert T3 values (@i * 5, @i * 11, @i)
set @i = @i + 1
end
GO
现在执行以下查询:
set statistics profile on
select *
from T1 join T2 on T1.a = T2.a
set statistics profile off
执行上述查询得到如下查询计划:
从输出信息了解到,T2表是T1表的10倍,而查询优化器则选择T1表作为"构建"表,T2表作为"探测"表.
下面来看一下三个表的联接:
set statistics profile on
select *
from (T1 join T2 on T1.a = T2.a)
join T3 on T1.b = T3.a
set statistics profile off
执行上述查询得到如下计划:
注意:查询优化器选择了基于Left Deep计划,首先,联接了两个较小的表:T1和T2,联接后产生了334行记录,这些行用于构建哈希表,然后与T3进行联接.
下面来看一下添加一个谓词来限制两个较小表的大小会发生什么情况?
set statistics profile on
select *
from (T1 join T2 on T1.a = T2.a)
join T3 on T1.b = T3.a
where T1.a < 100
set statistics profile off
注意:这一次与上一个查询不一样的是,使用了基于"right deep"计划.T1和T2表现在变得很小(34行和50行),在这两个表上构建哈希表为最佳选择.在哈希联接结果的中间表上构建哈希表,然后在T3表进行探测.
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/355374/viewspace-497811/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/355374/viewspace-497811/