MS SQL 查询联接运算系列--哈希联接(Hash Join)
哈希联接是第三种物理联接运算符,当说到哈希联接时,它是三种联接运算中性能最好的.嵌套循环联接适用于相对较小的数据集,而合并联接适用于中等规模的数据集,而哈希联接则适用于大规模联接的数据集.
哈希联接算法采用"构建"和"探测"两步来执行.在"构建"阶段,它首先从第一个输入中读取所有行(常叫做左或构建输入)在相等联接键上对这些行进行哈
希,然后在内存中创建哈希表,在"探测"阶段,从第二个输入中读取所有行(常叫做右中探测输入)在相的等值联接键上对这些行进行哈希,查找可探测该哈希表
中匹配的行.
下面是伪代码描述:
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
执行上述查询得到如下查询计划:
[img=550,189 alt=]http://www.haixiait.com/attachments/month_0804/v200841125633.JPG[/img]
从输出信息了解到,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
执行上述查询得到如下计划:
[img=550,191 alt=]http://www.haixiait.com/attachm
相关文档:
1 查询sql优化
1.1 选择最有效率的表名顺序(只在基于规则的优化器中有效ORACLE)
解析器按照从右到左的顺序处理from子句中的表名,因此from子句中写在最后的表(基础表driving table)将被最先处理。在from子句中包含多个表的情况下,你必须选择记录条数最少的表 ......
首先创建测试表、添加数据。
create table #t(a int,b int,c int,d int,e int)
insert into #t values(1,2,3,4,5)
insert into #t values(1,2,3,4,6)
insert into #t values(1,2,3,4,7)
insert into #t values(1,2,3 ......
在存储过程中使用事务,以下为模板:
CREATE PROCEDURE testPro
AS
/**//* ------- 事务开始---------- */
BEGIN TRANSACTION tran_test
/**//* -------- 保存事务----------*/
SAVE TRANSACTION tran_test
/**//* -------- 数据操作---------*/
INSERT [table1] ( [content] ) VALUES ( '43332' )
/**//*---- ......
今天安装sql server2000.系统是XP professional。首先先安装sqlserver企业版的,只能安装客户端;然后安装sqlserver开发版,就 被挂起,因此网上搜罗相关信息。
1、 若出现挂起后,可按下列操作进行,本人已经试用过:
在运行窗口输入regedit,打开注册表编辑器,在HKEY_LOCA ......
数据库备份 作业中的Sql语句:
DECLARE @strPath NVARCHAR(200)
set @strPath = convert(NVARCHAR(19),getdate(),120)
set @strPath = REPLACE(@strPath, ':' , '_')
set @strPath = REPLACE(@strPath, '-' , '_')
set @strPath = REPLACE(@strPath, ' ' , '_')
set @strPath = 'F:\数据库备份\' + myData_'+@s ......