join的三种方式

1、Using join buffer (Block Nested Loop)

  • 例如A表 Join B表,如TYPE类型是ALL或Index时候,则可以使用连接缓存(Join Buffer)
  • 官方示例代码:
    for each row in t1 matching range {
      for each row in t2 matching reference key {
        store used columns from t1, t2 in join buffer
        if buffer is full {
          for each row in t3 {
            for each t1, t2 combination in join buffer {
              if row satisfies join conditions, send to client
            }
          }
          empty join buffer
        }
      }
    }
    
    if buffer is not empty {
      for each row in t3 {
        for each t1, t2 combination in join buffer {
          if row satisfies join conditions, send to client
        }
      }
    }

2、索引join

  • 如果为连接列增加索引,则会通过索引匹配,而不需要到表里扫描
  • 比如A表JoinB表,A表为驱动表的情况下,如果B表的Join列有普通索引,则在外层循环(A表记录),里层循环(B表记录),替换里层循环的对象为索引,由于是普通索引,所以需要回表查询(相当于拿到主键ID之后还需要去遍历主键索引的B+树)
  • 如果上述的B表(非驱动表)的Join列是主键的话,则速度会更快,因为直接通过主键索引获取到数据,不需要再回表查询

3、普通join(A表外层循环,B表内层循环,挨个匹配)

   如果啥都没有,那只能挨个去匹配了,但一般会用第一种。

原文地址:https://www.cnblogs.com/gabin/p/13720517.html