数据库中多表连接的原理实现

2018-12-18  本文已影响0人  奥特曼打_小怪兽

多变关联的实现方式有hash join,merge join,nested loop join 方式,具体使用那种内型的连接,主要依据:

1.当前的优化器模式(all_rows和rule)

2.取决于表的大小

3.取决于关联字段是否有索性

4.取决于关联字段是否排序

Hash  join散列连接,优化器选择较小的表(数据量少的表)利用连接键(join key)在内存中建立散列表,将数据存储到hash列表中,然后扫描较大的表

select A.*,B.* from A left join B on a.id=b.id。

先是从A表读取一条记录,用on条件匹配B表的记录,行成n行(包括重复行)如果B表没有与匹配的数据,则select中B表的字段显示为空,接着读取A表的下一条记录,right join类似。

left join基本是A表全部扫描,在表关键中不建议使用子查询作为副表,比如select A.*,B.*from A left join (select * from b where b.type=1 )这样A表是全表扫描,B表也是全表扫描。若果查询慢,可以考虑关联的字段都建索引,将不必要的排序去掉,排序会导致运行慢很多。

主副表条件过滤:

table a(id, type):

id    type

----------------------------------

1      1       

2      1         

3      2   

表b结构和数据

table b(id, class):

id    class

---------------------------------

1      1

2      2

Sql语句1: select a.*, b.* from a left join b on a.id = b.id and a.type = 1;

执行结果为:

a.id    a.type    b.id    b.class

----------------------------------------

1        1            1        1

2        1            2        2

3        2

a.type=1没有起作用

sql语句2:

select a.*, b.* from a left join b on a.id = b.id where a.type = 1;

执行结果为:

a.id    a.type    b.id    b.class

----------------------------------------

1        1            1        1

2        1            2        2

sql语句3:

select a.*, b.* from a left join b on a.id = b.id and b.class = 1;

执行结果为:

a.id    a.type    b.id    b.class

----------------------------------------

1        1            1        1

2        1           

3        2

b.class=1条件过滤成功。

结论:left join中,左表(主表)的过滤条件在on后不起作用,需要在where中添加。右表(副表)的过滤条件在on后面起作用。

Mysql join原理:

Mysql join采用了Nested Loop join的算法,

###坐车 回去补充。

上一篇下一篇

猜你喜欢

热点阅读