表关联Join的本质

839 阅读1分钟

在数据库操作中会经常出现Join的操作,知晓Join的底层算法(本质),那么对于执行计划的理解,以及性能优化,有着很大的帮助。

一 Inner join

inner join 有三种连接方式

嵌套循环连接(nested loops join)

1.hard code

for each row R1 in the outer table
	for each row R2 in the inner table 
		if R1 join R2
			return(R1,R2)

2.特点

外少内多,消耗=内*外,笛卡尔积。
不适合2张大表
易引起I/O问题

合并连接(merge join)

1.hard code

ResultEntity result = new ResultEntity();
while(!left.IsPastEnd()&&!right.IsPastEnd()){
	if(left.key == right)
	{
		result.add(left,right);
		left.Advance();
		right.Advance();
	}
	else if(left.key<right.key){
		left.Advance();
	}
	else{
		right.Advance();
	}
}
return result;

2.特点

适合中表
2张表预先排序。对表只读一次。
必须有等值连接。
如果tsql里有orderby,groupby,distinct基本上就舍弃hash join,选择merge join

哈希连接(hash join)

1.hard code

for each row R1 in the build table
begin
	y=for(R1)  -- hash计算
	insert into hash buck  --hash计算之后 ,数据插入hash桶
end
for each row R2 in the match table
begin
	y=for(R2)  --hash计算
	for each row R1 in the hash buck  --R2, 和R1的hash 桶的值比对 
		if R1 join with R2
			result.add(R1,R2)
end

2.特点

适合大表,不要求列有排序
缺点:占用大量内存,cpu。

二 Outer Join

Left join | Right Join | Full join
未找到匹配的数据 —— null填充

三 Cross Join

笛卡尔积,得到表的所有组合。左表M,右表N ,返回M*N数据