SQL JOIN-Hash Join
1概述
hash join 在特性與merge join相同,都需要一個等值條件。當在連接條上無法命中索引,或大集合的Join, nested join和 merge join可能就無法得到很好的性能,這時我們就需要考慮用hash join.
2基本算法
Hash join 分為兩個階段,build和probe。在build階段,會將其中一個集合作為build set,然后hash build table在連接條件上的列,并將結果存儲在內存中的(命名為build hash table). ?在probe階段(將第二個集合命名為probe set),每一行hash probe set在連接條件上的列,然后與build hash table比較,如果相等,則返回。
偽代碼:
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
??????????????? return (R1, R2)
??? end
3 示例
測試數據
View Code 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 ondeclare @i intset @i = 0while @i < 1000begininsert T1 values (@i * 2, @i * 5, @i)set @i = @i + 1endset @i = 0while @i < 10000begininsert T2 values (@i * 3, @i * 7, @i)set @i = @i + 1endset @i = 0while @i < 100000begininsert T3 values (@i * 5, @i * 11, @i)set @i = @i + 1end執行SQL:
SET STATISTICS PROFILE ON select * from (T1 inner join T2 on T1.a = T2.a)inner join T3 on T1.b = T3.a option (hash join)執行結果:
總結
以上是生活随笔為你收集整理的SQL JOIN-Hash Join的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【一天一个shell命令】好管家-磁盘-
- 下一篇: 给vs2012轻松换肤